Error handling in Apollo Server GraphQL not redirecting to login page

// Error handling code in Apollo Client
onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) => {
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      );

      if (message.includes("not authenticated")) {
        if (typeof window === "undefined") {
          ctx.res?.writeHead(302, { Location: "/login" });
          ctx.res?.end();
        } else {
          useRouter().replace("/login");
        }
      } else {
        console.log("dispatch");
      }
    });
  }
  if (networkError) console.error(`[Network error]: ${networkError}`);
})

I have tried to use Apollo Client error handling to detect the ‘not authenticated’ error and redirect the user to the login page. I expected that when this error occurs, the application would redirect the user to the ‘/login’ page. However, instead, I am getting an error that looks like this.
[Network error]: TypeError: forward is not a function

import { NextPageContext } from "next";
import { createWithApollo } from "./createWithApollo";
import { ApolloClient, ApolloLink, InMemoryCache } from "@apollo/client";
import { onError } from "@apollo/client/link/error";
import { useRouter } from "next/navigation";


const createClient = (ctx: NextPageContext) =>
  new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.forEach(({ message, locations, path }) => {
            console.log(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
            );

            if (message.includes("not authenticated")) {
              if (typeof window === "undefined") {
                ctx.res?.writeHead(302, { Location: "/login" });
                ctx.res?.end();
              } else {
                useRouter().replace("/login");
              }
            } else {
              console.log("dispatch");
            }
          });
        }
        if (networkError) console.error(`[Network error]: ${networkError}`);
      })
    ]),
    uri: process.env.NEXT_PUBLIC_API_URL as string,
    credentials: "include",
    headers: {
      cookie:
        (typeof window === "undefined"
          ? ctx?.req?.headers.cookie
          : undefined) || "",
    },
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            companieQuote7Days: {
              merge(existing = [], incoming) {
                return incoming;
              },
            },
          },
        },
        COMPANIE: {
          fields: {
            companieQuotes: {
              merge(existing = [], incoming) {
                return incoming;
              },
            },
          },
        },
        COMPANIEQUOTE: {
          fields: {
            productQuotes: {
              merge(existing = [], incoming) {
                return incoming;
              },
            },
          },
        },
      },
    }),
  });

export const withApollo = createWithApollo(createClient);

  • This is a problem with how you are using the next router, nothing to do with GraphQL.

    – 

Leave a Comment