Redirect to a new page in getInitialProps using Next.js?

Unanswered
coderguy asked this question 11 months ago
coderguy on Jun 26, 2022

In my getInitialProps() function, I make a request to my REST API.

static async getInitialProps({ query, req, res }) {
  const apiResult = await getImageByFilename(query.filename, req);

  return {
    data: apiResult.data,
  };
}

Based on data in the result from the API, I want to conditionally redirect to a new page.

How would I do that? Is there a way to do that in Next.js?

1 suggested answers
looper003 on Jun 26, 2022

You can use res.writeHead() to do this. This will allow you to set a new location on the response header.

To do this, you can update your getInitialProps() function to this:

static async getInitialProps({ query, req, res }) {
  const apiResult = await getImageByFilename(query.filename, req);

  if (boolean) {
    res.writeHead(302, {
      Location: "/different-page"
    });

    res.end();
  }

  return {
    data: apiResult.data,
  };
}

If the given boolean value is true, you'll be redirected to the /different-page page.

The 302 code indicates that it's a redirect.

0 replies
Unanswered