Next.js Redirect from / to another page

When working with Next.js, you may come across a situation where you need to redirect users from one page to another. In this blog post, we will explore how to redirect from the root page (“/”) to another page using Next.js.

Using the useRouter Hook

One way to achieve the redirect is by using the useRouter hook provided by Next.js. This hook gives us access to the router object, which allows us to programmatically navigate to different pages.

Here’s an example of how you can redirect from the root page to another page:

{`import { useRouter } from 'next/router';
import { useEffect } from 'react';

const Home = () => {
  const router = useRouter();

  useEffect(() => {
    router.push('/another-page');
  }, []);

  return null;
};

export default Home;`}

In this example, we import the useRouter hook from the ‘next/router’ module and the useEffect hook from ‘react’. We then create a functional component called Home, which represents the root page (“/”).

Inside the Home component, we initialize the router object using the useRouter hook. We then use the useEffect hook to perform the redirect when the component mounts. The router.push(‘/another-page’) method is called to navigate to the “/another-page” route.

Using the Redirect Component

Another way to achieve the redirect is by using the Redirect component provided by Next.js. This component allows us to declaratively specify the destination page.

Here’s an example of how you can use the Redirect component to redirect from the root page to another page:

{`import { Redirect } from 'next';

const Home = () => {
  return ;
};

export default Home;`}

In this example, we import the Redirect component from the ‘next’ module. We then create a functional component called Home, which represents the root page (“/”).

Inside the Home component, we use the Redirect component and specify the href prop as “/another-page” to indicate the destination page.

Conclusion

In this blog post, we explored two different ways to redirect from the root page to another page using Next.js. Both methods, using the useRouter hook and the Redirect component, provide a straightforward solution to achieve the desired redirect.

Remember to choose the method that best suits your project’s requirements and coding style. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *