Authentication

Fine tune how the GraphQL client(s) are authenticated.

Token Storage

There are two (2) supported token storage modes, These include localStorage and cookie, with the latter being the default and recommended option.

Local Storage

The local storage mode can be enabled by setting the tokenStorage.mode property to localStorage. This can be applied on a per-client basis, or globally.

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],

  'graphql-client': {
    tokenStorage: {
      mode: 'localStorage'
    }
  }
})
Doesn't support server-side rendering (SSR).

Due to localStorage being a browser-only feature, it is not possible to use this mode with server-side rendering (SSR).

Cookie storage is the recommended approach and is also required for server-side rendering (SSR).

Configured clients provide a proxyCookies option (enabled by default) which when enabled, will proxy all cookies from the client to the server. This is particularly useful for server-side rendering (SSR).

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],

  'graphql-client': {
    tokenStorage: {
      name: '__session',
      mode: 'cookie', // default
      cookieOptions: {
        path: '/',
        secure: false, // defaults to `process.env.NODE_ENV === 'production'`
        httpOnly: false, // Only accessible via HTTP(S)
        maxAge: 60 * 60 * 24 * 5 // 5 days
      }
    }
  }
})

secure

When set to true, The secure cookie option ensures that cookies are only sent over HTTPS connections.

httpOnly

The httpOnly cookie option is supported with minimal effort on your part. This option prevents cookies from being accessed by JavaScript.

Auth Initialization Hook

This module attempts to retrieve the authentication token via the configured tokenStorage.

The gql:auth:init hook allows you to override the aforementioned behavior, and provide custom logic for manually retrieving and applying the authentication token accordingly. This should account for Multiple Client Mode, as well as both client and server side contexts.

Tokens set via the gql:auth:init hook adhere to the same token configuration of the pertinent client.

plugins/auth.ts
export default defineNuxtPlugin((nuxtApp) => {
  // access cookie for auth
  const cookie = useCookie('<cookie_name>')

  nuxtApp.hook('gql:auth:init', ({ client, token }) => {
    // `client` can be used to differentiate logic on a per client basis.

    // apply client token
    token.value = '<secret_token>'
  })
})
Nuxt composables such as useState, useCookie, useRequestHeaders and more, should not be called directly in the gql:auth:init hook. This would result in a nuxt instance unavailable error on the server-side.

Authenticated Requests

Make authenticated requests to the GraphQL APIs.

nuxt-graphql-client provides a useGqlToken composable to attach an authorization header to subsequent requests.

Any requests made after the token is set will be sent with the authenticaion header configured by useGqlToken.

login.vue
<script lang="ts" setup>
// your auth logic...

function afterLogin(idToken: string) {
    useGqlToken(idToken)
}
</script>

More information at useGqlToken composable

Provide Token

A token can be provided to the default client via the GQL_TOKEN environment variable.

.env
GQL_TOKEN="your_access_token"

Provide Token for a specific client

Given a client named github, The token can be provided via the GQL_GITHUB_TOKEN environment variable.

.env
GQL_GITHUB_TOKEN="your_access_token"

Custom Token

The default authorization header is Authorization with an auth scheme of Bearer. These can be customized either:

  • In the client token configuration options.
  • When using the useGqlToken composable.

Given a client named shopify

The token can either be configured in the .env file or in the Nuxt Configuration.

.env
GQL_SHOPIFY_TOKEN="your_access_token"
GQL_SHOPIFY_TOKEN_NAME="X-Shopify-Access-Token"
nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
    modules: ['nuxt-graphql-client'],

    runtimeConfig: {
        public: {
            'graphql-client': {
                clients: {
                    default: 'https://api.spacex.land/graphql', // overwritten by process.env.GQL_HOST 
                    shopify: {
                        host: '', // overwritten by process.env.GQL_SHOPIFY_HOST 
                        token: {
                            name: 'X-Shopify-Access-Token', // overwritten by process.env.GQL_SHOPIFY_TOKEN_NAME
                            value: 'your_access_token', // overwritten by process.env.GQL_SHOPIFY_TOKEN
                            type: 'Bearer' // defaults to 'Bearer'
                        }
                    }
                }
            }
        }
    }
})

Server Side Only

Authentication tokens added to either the Nuxt configuration or environment variables will only live server side, hence these tokens can only be used for Build Time SSR or Code Generation Introspection

nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
    modules: ['nuxt-graphql-client'],

    runtimeConfig: {
        public: {
            'graphql-client': {
                clients: {
                    default: 'https://api.spacex.land/graphql',
                    github: {
                        host: 'https://api.github.com/graphql',
                        token: '<your-github-token>' // overwritten by process.env.GQL_GITHUB_TOKEN
                    }
                }
            }
        }
    }
})
.env
GQL_GITHUB_TOKEN="<your-github-token>"

Retain Token Client-Side

To circumvent the default behavior mentioned in the Server Side Only section, you can use the retainToken flag to force a token set at config-level ( by runtimeConfig or environment variables ) to be retained on the client side.

This flag exposes the token to the client side, which can be a security risk.
Only use this flag if you understand the security implications.
nuxt-config.ts
export default defineNuxtConfig({
    modules: ['nuxt-graphql-client'],

    runtimeConfig: {
        public: {
            'graphql-client': {
                clients: {
                    default: 'https://api.spacex.land/graphql',
                    github: {
                        host: 'https://api.github.com/graphql',
                        token: '<your-github-token>',
                        retainToken: true
                    }
                }
            }
        }
    }
})

Codegen Introspection

Authorization is often required to run the introspection query for many GraphQL APIs (e.g. Github GraphQL API).

This module attempts to generate types for your GraphQL APIs using the introspection query, Hence this process may fail if the API requires authentication.

In this instance, an authentication token must be provided to the pertinent client by either:

  • Configuring the client in your nuxt configuration
  • Adding the token to your .env (Recommended)
This token will only live server-side. It will not be passed to the browser.