What is the difference in Next.js between
return {
redirect: {
permanent: false,
destination: ''
}
};
And
res.redirect()
What is the difference in Next.js between
return {
redirect: {
permanent: false,
destination: ''
}
};
And
res.redirect()
Generally speaking, they achieve the same goal but are used in different contexts.
redirect object in getServerSidePropsReturning 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.
res.redirect() in API routesIn 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, '/')