'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
redirectobject 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 olderHTTPclients to properly redirect. In these cases, you can use thestatusCodeproperty instead of thepermanentproperty, 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.statusmust be a valid HTTP status code. If not specified,statusdefaults 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 |
