Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nextjs RangeError: Maximum call stack size exceeded

import React from "react";
import "../assets/style/global.scss";
import cookies from "next-cookies";
import client from "../lib/api/client";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

MyApp.getInitialProps = async (appContext) => {
  const appProps = await MyApp.getInitialProps(appContext);
  const { ctx } = appContext;
  const allCookies = cookies(ctx);
  const token = allCookies["accessToken"];
  if (token !== undefined) {
    client.defaults.headers.Authorization = token;
  }

  return { ...appProps };
};

export default MyApp;

When logging in, we try to put the access token in a cookie and put the cookie value in the header in every api request. But I get this error. How can I fix it?

like image 579
Sour_sr Avatar asked Feb 05 '26 23:02

Sour_sr


1 Answers

You get that error because you're generating an infinite loop by calling MyApp.getInitialProps(appContext) inside MyApp.getInitialProps.

Simply replace that line with an App.getInitialProps call instead.

// ...
import App from 'next/app'

// ...

MyApp.getInitialProps = async (appContext) => {
    const appProps = await App.getInitialProps(appContext);
    // ...

    return { ...appProps };
};
like image 120
juliomalves Avatar answered Feb 08 '26 15:02

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!