Fikri Lazuardi
Fikri Lazuardi

Reputation: 11

getting cookies from apollo client on next js

I want to get the cookie with my client component, but somehow, it always return undefined or empty string. I am using js-cookie since someone recommend it.

ApolloProviderClient.tsx:

"use client";

import React from "react";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  ApolloLink,
  HttpLink,
} from "@apollo/client";
import { SSRMultipartLink } from "@apollo/experimental-nextjs-app-support";
import { setContext } from "@apollo/client/link/context";
import Cookies from "js-cookie";

export default function ApolloProviderClient({
  children,
}: React.PropsWithChildren) {
  const httpLink = new HttpLink({
    uri: "http://localhost:4000/",
  });

  // Middleware to add Authorization header dynamically
  const authLink = setContext((_, { headers }) => {
    const accessToken = Cookies.get("accessToken");
    // DEBUGGING: Log all cookies
    console.log(accessToken);

    return {
      headers: {
        ...headers,
        Authorization: accessToken ? `Bearer ${accessToken}` : "",
      },
    };
  });



const client = new ApolloClient({
    cache: new InMemoryCache(),
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            // in a SSR environment, if you use multipart features like
            // @defer, you need to decide how to handle these.
            // This strips all interfaces with a `@defer` directive from your queries.
            new SSRMultipartLink({
              stripDefer: true,
            }),
            authLink.concat(httpLink),
          ])
        : authLink.concat(httpLink),
    credentials: "include",
  });

  return <ApolloProvider client={client}>{children}</ApolloProvider>;
}

Questions:

  1. Why is Cookies.get() returning undefined or an empty string?
  2. Are there any common pitfalls or mistakes I might be making when using js-cookie?
  3. Is there a better way to retrieve cookies in a client-side React component?

Any help or guidance would be greatly appreciated!

Upvotes: 1

Views: 18

Answers (1)

Ian Carter
Ian Carter

Reputation: 2169

Several things need to be verified to debug cookies with Apollo Client in NextJS:

  • Check browser cookies: Open DevTools → Application → Cookies
  • Is the cookie HttpOnly? If yes, it’s not accessible via JavaScript
  • Same-origin issue? Make sure frontend and backend share the same domain or configure CORS properly
  • Is credentials: "include" set? Both in ApolloClient and backend
  • Is the cookie being set correctly? Set-Cookie header should include Path=/; HttpOnly; Secure; SameSite=Lax
  • Add console.debug(Cookies.get()) before initializing Apollo Client
  • Backend CORS config e.g.: {origin: "http://localhost:3000", credentials: true}
    "use client";

    import React, { useEffect } from "react";
    import {
        ApolloClient,
        InMemoryCache,
        ApolloProvider,
        ApolloLink,
        HttpLink,
    } from "@apollo/client";
    import { setContext } from "@apollo/client/link/context";
    import Cookies from "js-cookie";

    export default function ApolloProviderClient({ children }: React.PropsWithChildren) {
        // Debugging: Ensure cookies are available
        useEffect(() => {
            console.log("Cookies Available:", Cookies.get());
        }, []);

        const httpLink = new HttpLink({
            uri: "http://localhost:4000/",
            credentials: "include", // Important for sending cookies
        });

        const authLink = setContext((_, { headers }) => {
            const accessToken = Cookies.get("accessToken");
            console.debug("Access Token:", accessToken);

            return {
                headers: {
                    ...headers,
                    Authorization: accessToken ? `Bearer ${accessToken}` : "",
                }
            };
        });

        const client = new ApolloClient({
            cache: new InMemoryCache(),
            link: authLink.concat(httpLink),
            credentials: "include",
        });

        return <ApolloProvider client={client}>{children}</ApolloProvider>;
    }

Upvotes: 0

Related Questions