How to redirect from / to another page with Next.js?

Sometimes, we want to redirect from / to another page with Next.js.

In this article, we’ll look at how to redirect from / to another page with Next.js.

How to redirect from / to another page with Next.js?

To redirect from / to another page with Next.js, we can get the pathname property from the Router object and do the redirect if pathname is '/'.

For instance, we write

import React, { useEffect } from "react";
import Router from "next/router";

const Comp = () => {
  //...
  useEffect(() => {
    const { pathname } = Router;
    if (pathname === "/") {
      Router.push("/hello-nextjs");
    }
  });
  //...
};

to call get pathname from Router.

And if pathname is '/', then we call Router.push to go to the URL we want.

This works with Next.js 10.x

Conclusion

To redirect from / to another page with Next.js, we can get the pathname property from the Router object and do the redirect if pathname is '/'.