Unanswered
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?
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.