I'm trying to make a private page with Next.js.
I wrote pages/private.tsx
.
import React from 'react';
import { Label } from '@components/atoms';
import { Layout } from '@components/Layout';
import Link from 'next/link';
import { GetServerSideProps } from 'next';
const Private = (props: any) => {
console.log(props);
return (
<Layout>
<Link href="/">
<a>
<Label size="L1" margin="32px 0 0 24px" pointer>
Go Back to Home
</Label>
</a>
</Link>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// redirect test: always redirect to '/login'
ctx.res.setHeader('Location', '/login');
ctx.res.statusCode = 302;
ctx.res.end();
return {
props: {},
};
};
export default Private;
It works well. If I try to go /private
, it redirects to /login
.
Browser is OK, but my console said,
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at DevServer.sendHTML (Directory/node_modules/next/server/next-dev-server.ts:663:9)
at DevServer.render (Directory/node_modules/next/next-server/server/next-server.ts:1232:17)
at Object.fn (Directory/node_modules/next/next-server/server/next-server.ts:726:11)
at Router.execute (Directory/node_modules/next/next-server/server/router.ts:247:24)
at DevServer.run (Directory/node_modules/next/next-server/server/next-server.ts:1158:23)
at DevServer.handleRequest (Directory/node_modules/next/next-server/server/next-server.ts:551:14) {
code: 'ERR_HTTP_HEADERS_SENT'
}
The reason I think is after the server sent response to browser, I tried to send 302 status code again.
Is there a way to fix this error?
++ I tried to make redirection code in Client-Side, but it shows private page for a second and redirected. I want to block in the initial loading.
We can redirect from the server-side by returning a redirect key. The destination is the path we want to route to.
To redirect from / to another page with Next. js, we can get the pathname property from the Router object and do the redirect if pathname is '/' . import React, { useEffect } from "react"; import Router from "next/router"; const Comp = () => { //...
Solution #1: getInitialProps() To do a quick recap, getInitialProps() is a function/method that lets you write server code before the page component in Next. JS gets rendered. In that function/method you can redirect a user to an internal or external URL via the server side.
You can return this
return {
redirect: {
permanent: false,
destination: "/login",
},
props:{},
};
instead of setting header.
That error arrived due to two responses sent by the serversideprops. One in the return and one by header.
You can read more about redirect here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With