Reputation: 61
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
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