'Difference between redirect object and res.redirect in Next.js

What is the difference in Next.js between

return {
  redirect: {
    permanent: false,
    destination: ''
  }
};

And

res.redirect()


Solution 1:[1]

Generally speaking, they achieve the same goal but are used in different contexts.

#1 Using redirect object in getServerSideProps

Returning a redirect object from getServerSideProps is essentially a more idiomatic and valid way of redirecting to another path from within that function. From the documentation:

The redirect object allows redirecting to internal and external resources. It should match the shape of { destination: string, permanent: boolean }. In some rare cases, you might need to assign a custom status code for older HTTP clients to properly redirect. In these cases, you can use the statusCode property instead of the permanent property, but not both.

It ends up (roughly) executing the following code internally:

res.statusCode = 307
res.setHeader('Location', '/')
res.end()

In your first code block the redirect will be executed with status code 307, due to the permanent: false value.

#2 Using res.redirect() in API routes

In Next.js, the res.redirect() method can be used within API routes to redirect to the specified path. From the documentation:

res.redirect([status,] path) - Redirects to a specified path or URL. status must be a valid HTTP status code. If not specified, status defaults to "307" "Temporary redirect".

It can be used as follows, where a status code and path are passed to it:

res.redirect(307, '/')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1