在 apollo 客户端 NextJS13 中处理身份验证令牌过期

问题描述 投票:0回答:1

我正在尝试处理 NextJS 13 应用程序中 GraphQL、Apollo 客户端中身份验证令牌的过期问题。这是我为客户端提供商编写的代码,

"use client";

import React from "react";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  HttpLink,
  ApolloLink,
  concat,
} from "@apollo/client";

const httpLink = new HttpLink({ uri: process.env.NEXT_PUBLIC_SANDBOX_URL });

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers
  operation.setContext(({ headers = {} }) => ({
    headers: {
      ...headers,
      authorization: localStorage.getItem("AuthToken") || null,
    },
  }));
  return forward(operation);
});

export const client = new ApolloClient({
  link: concat(authMiddleware, httpLink),
  cache: new InMemoryCache(),
});

const ApolloClientProvider = ({ children }) => {
  return <ApolloProvider client={client}>{children}</ApolloProvider>;
};

export default ApolloClientProvider;

由于我是 apollo 客户端的新手,我想在身份验证令牌过期时编写一些自定义函数。我无法找到任何最好的方法来处理它。任何对此的帮助将不胜感激。

graphql apollo-client next.js13 react-apollo
1个回答
0
投票

您可以使用 apollo-link-error 包来处理网络和 GraphQL 错误。

样品:

const errorLink = onError(({ networkError }) => {
  if (networkError && networkError.statusCode === 401) {
    // Handle token expiration here. 401 (Unauthorized) 
    //checks for a 401 status, and then performs a token refresh 
  }
});

export const client = new ApolloClient({
  link: ApolloLink.from([authMiddleware, errorLink, httpLink]),
  cache: new InMemoryCache(),
});
© www.soinside.com 2019 - 2024. All rights reserved.