How to redirect to a page with Next.js

Learn the ways to redirect users to another page with Next.js

Depending on whether we are redirecting from an API endpoint or from a server-side rendering function, there are different ways to redirect users to another page using Next.js.

Redirecting from an API function in Next.js

If you are handling an API function, you can use the redirect method on the NextApiResponse object to redirect the user to another page, as seen below:

function myApiHandler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (notFound()) {
return res.redirect(HttpStatusCode.NotFound, `/404`);
}
}
export default myApiHandler;

Redirecting users before rendering the page in Next.js

Another common way to redirect users to another page is using the getServerSideProps function when rendering the page server-side with Next.js.

This function is particularly useful, for example, when checking the authentication state of the user before rendering the correct page.

To do so, we have to return the object containing redirect as a property from the gerServerSideProps function with the following interface:

{
redirect: {
permanent: boolean;
destination: string;
}
}

Let's see a complete example:

export default function ProtectedPage() {
return <></>;
}
export function getServerSideProps(ctx: GetServerSidePropsContext) {
if (isLoggedIn()) {
const props = getProps();
return {
props,
}
}
const destination = `/auth/sign-in?returnUrl=${returnUrl}`;
return {
redirect: {
permanent: false,
destination,
},
};
}

And that's it! You now know everything you need to be able to redirect users to other pages with Next.js!