Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

530
Views
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;
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 {};
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!