I’m building a Next.js 14 app with Apollo Client configured for server-side rendering (SSR). I need to access cookies on the server to include an authentication token in the Apollo request headers. However, I’m unable to access cookies using request.cookies.get('accessToken')?.value
within the server-side rendering context. This apolloConfig
is working perfectly fine in the client side using the porvider setup. but I wanna use this in the SSR as well.
apollo-config.ts:
import { createHttpLink, from } from '@apollo/client';
import { InMemoryCache } from '@apollo/experimental-nextjs-app-support';
import { setContext } from '@apollo/client/link/context';
import Cookies from 'js-cookie';
import { Auth } from './constants';
const httpLink = createHttpLink({
// this needs to be an absolute url, as relative urls cannot be used in SSR
uri: process.env.NEXT_PUBLIC_GRAPHQL_URI,
// you can disable result caching here if you want to
// (this does not work if you are rendering your page with `export const dynamic = "force-static"`)
// fetchOptions: { cache: "no-store" },
});
const authLink = setContext(async (_, { headers }) => {
const accessToken = Cookies.get(Auth.Tokens.AccessToken);
if (!accessToken) {
return { headers };
}
return {
headers: {
...headers,
authorization: `Bearer ${accessToken}`,
},
};
});
export const apolloConfig = {
cache: new InMemoryCache(),
link: from([authLink, httpLink]),
connectToDevTools: true,
};
apollo-client.ts:
import { HttpLink } from '@apollo/client';
import {
registerApolloClient,
ApolloClient,
InMemoryCache,
} from '@apollo/experimental-nextjs-app-support';
import { apolloConfig } from './apollo-config';
export const { getClient } = registerApolloClient(() => {
return new ApolloClient(
apolloConfig
);
});
export const apollo = getClient();
Question:
How can I access cookies within the server-side rendering context of my Next.js app to include an authentication token in Apollo requests? I’m specifically interested in using request.cookies.get(‘accessToken’)?.value or a similar approach. FYI I wanna solve this issue in the apollo config file so that I can have a unified config for both client side and server side.
I have tried almost everything that could be done, but I don’t get how I can access the request object like how we would do it in middleware.ts