I'm trying to handle the expiration of auth token in GraphQL, Apollo client in NextJS 13 application. This is the code I've written for the client provider,
"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;
Since I'm new to apollo client I want to write some custom function when the auth token expires. I couldn't able to find any best way to handle it. Any help on this would be appreciated.
You may use the apollo-link-error package to handle network and GraphQL errors.
Sample: