diff --git a/src/runtime/plugin.ts b/src/runtime/plugin.ts index 9263dbc1..aae0f6f6 100644 --- a/src/runtime/plugin.ts +++ b/src/runtime/plugin.ts @@ -6,6 +6,7 @@ import { ApolloClients, provideApolloClients } from '@vue/apollo-composable' import { ApolloClient, ApolloLink, createHttpLink, InMemoryCache, split } from '@apollo/client/core' import { GraphQLWsLink } from '@apollo/client/link/subscriptions' import { setContext } from '@apollo/client/link/context' +import type { ClientOptions } from 'graphql-ws' import type { ClientConfig, ErrorResponse } from '../types' import createRestartableClient from './ws' import { useApollo } from './composables' @@ -76,11 +77,24 @@ export default defineNuxtPlugin((nuxtApp) => { ...clientConfig.wsLinkOptions, url: clientConfig.wsEndpoint, connectionParams: async () => { + let connectionParams: ClientOptions['connectionParams'] = clientConfig.wsLinkOptions?.connectionParams || {} + + // if connection params is a function, call it + if (typeof connectionParams === 'function') { + connectionParams = await connectionParams() + } + const auth = await getAuth() + if (!auth) { return connectionParams } - if (!auth) { return } + // merge connection headers with the auth header + const headers = { + [clientConfig.authHeader!]: auth, + ...(connectionParams?.headers || {}) + } - return { headers: { [clientConfig.authHeader!]: auth } } + // merge existing connection params with headers + return { ...connectionParams, headers } } }) diff --git a/src/types.d.ts b/src/types.d.ts index f9d41f72..7b106922 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -29,7 +29,7 @@ export type ClientConfig = { * Provide additional configuration for the `GraphQLWsLink`. * See https://github.com/enisdenjo/graphql-ws/blob/master/docs/interfaces/client.ClientOptions.md **/ - wsLinkOptions?: Omit; + wsLinkOptions?: Omit; /** * Specify a websocket endpoint to be used for subscriptions.