Next.js getServerSideProps redirection ERR_HTTP_HEADERS_SENT error

Viewed 23371

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.

1 Answers

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

Related