next.js Apollo客户端上下文中没有标头

jgwigjjp  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(114)

我在我的应用程序中使用基于cookie的身份验证。为了验证我的请求,我想出了这段代码:

import { HttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { ACCESS_TOKEN_COOKIE_NAME } from "constants/cookies";
import { getCookie } from "./cookies";

const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;

// eslint-disable-next-line import/prefer-default-export
export const getApolloClientLink = () => {
  const httpLink = new HttpLink({
    uri: `${apiBaseUrl}/graphql`,
    // Pass credentials to the server
    credentials: "same-origin",
  });

  const authLink = setContext(async (_, { headers }) => {
    console.log("Current headers", headers);

    // Get the authentication token from apollo context if it exists
    const existingToken = headers?.authorization;

    if (existingToken) {
      console.log("WE HAVE A TOKEN", existingToken);
      return {
        headers: {
          ...headers,
          authorization: existingToken,
        },
      };
    }

    console.log("NO TOKEN");
    // If no token is found, get it from cookies
    const token = await getCookie(ACCESS_TOKEN_COOKIE_NAME);

    console.log("updated headers:", {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token.value}` : "",
      },
    });

    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token.value}` : "",
      },
    };
  });

  return authLink.concat(httpLink);
};

字符串
这为我提供了它传递给我的apollo客户端的链接:

export const { getClient } = registerApolloClient(
  () =>
    new NextSSRApolloClient({
      cache: new NextSSRInMemoryCache(),
      link: getApolloClientLink(),
    }),
);


不幸的是,它总是记录“NO TOKEN”,当记录我的头的值时,它总是返回undefined。我错过了什么吗?

cngwdvgl

cngwdvgl1#

这些头是Next服务器发送到GraphQL服务器的请求的头-它们与浏览器发送到Next服务器的请求的头没有任何关系。您必须使用Next.js headers()cookies()函数。

相关问题