itwaze
itwaze

Reputation: 199

How to redirect user to another page using getServerSideProps?

I found this solution:

export const getServerSideProps = async ({ res }) => {
  res.redirect(301, '/another-page')
  
  return {
    props: {}
  }
}

but I don't see redirect method in the res and get an error

Upvotes: 0

Views: 1204

Answers (2)

Hooman
Hooman

Reputation: 1925

A cleaner approach would be look like this:

export const getServerSideProps = async ({ res }) => {
  res.writeHead(302, { Location: '//another-page/' });
  res.end()
  return;
}

I would suggest you to use Status code 302 instead of 301

Hope it helps!

Upvotes: 1

Stefano Giometti
Stefano Giometti

Reputation: 433

Seems like you're using Next.js. Try something like this.

export const getServerSideProps = async ({ res }) => {
  res.setHeader("location", "/another-page")
  res.statusCode = 301
  res.end()
  return;
}

Upvotes: 1

Related Questions