Maruko
Maruko

Reputation: 61

Infinite loop when redirecting in getInitialProps in Next.js

I have just learn Next.js and I have one problem with getInitialProps in _app.jsx. I don't know why have an infinite loop error. Please tell me why infinite loop and how to fix it.

const MyApp = ({ Component, pageProps }) => {

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

MyApp.getInitialProps = async ({ ctx }) => {
  console.log("run 1");
  if (ctx.res) {
    console.log("run here");
    ctx.res.writeHead(302, {
      Location: "/login",
    });
    ctx.res.end();
  }
  return {};
};

export default MyApp;

Upvotes: 3

Views: 2763

Answers (1)

juliomalves
juliomalves

Reputation: 50308

The infinite loop happens because the redirect also happens when you're on the /login page. To prevent it, make sure no redirection happens when you're on that page.

MyApp.getInitialProps = async ({ ctx }) => {
    if (ctx.res && ctx.asPath !== "/login") {
        ctx.res.writeHead(302, {
            Location: "/login",
        });
        ctx.res.end();
     }
     return {};
};

Upvotes: 2

Related Questions