apollo-client-nextjs icon indicating copy to clipboard operation
apollo-client-nextjs copied to clipboard

Next14 initialize ApolloWrapper with Cookie

Open ptrtorain opened this issue 2 years ago • 0 comments

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>
    );
}

ptrtorain avatar Dec 09 '23 05:12 ptrtorain