apollo-client-nextjs
apollo-client-nextjs copied to clipboard
Next14 initialize ApolloWrapper with Cookie
Hello, I needed to initialize ApolloWrapper with an Authorization header (Cookie), so I made a few changes to make it work. Do you have any comments about this decision? If I open a PR, I'll make some breaking changes in your API in order to support Cookies.
"use client";
import {
ApolloNextAppProvider,
NextSSRInMemoryCache,
NextSSRApolloClient,
SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support/ssr";
import { ApolloLink, HttpLink } from "@apollo/client";
function makeClient(cookie: string) {
const httpLink = new HttpLink({
fetchOptions: { cache: "no-store" },
headers: { authorization: cookie }, // <= our token
uri: process.env.NEXT_PUBLIC_URL,
credentials: "include";
});
return new NextSSRApolloClient({
link:
typeof window === "undefined"
? ApolloLink.from([
new SSRMultipartLink({
stripDefer: true,
}),
httpLink,
])
: httpLink,
cache: new NextSSRInMemoryCache(),
});
}
export function ApolloWrapper({ children, cookie }: React.PropsWithChildren<{ cookie: string }>) {
const initializeClientWithCookie = () => makeClient(cookie); // initialize ApolloWrapper with Cookie
return (
<ApolloNextAppProvider makeClient={initializeClientWithCookie}>
{children}
</ApolloNextAppProvider>
);
}