Reputation: 11
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:
Any help or guidance would be greatly appreciated!
Upvotes: 1
Views: 18
Reputation: 2169
Several things need to be verified to debug cookies with Apollo Client in NextJS:
Path=/; HttpOnly; Secure; SameSite=Lax
console.debug(Cookies.get())
before initializing Apollo Client{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