Categories
React Answers

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

Spread the love

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");
    }
  });
  //...
};

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.