Handling auth token expiration in apollo client NextJS13

74 Views Asked by At

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.

1

There are 1 best solutions below

0
Parklan Poon On

You may use the apollo-link-error package to handle network and GraphQL errors.

Sample:

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(),
});