Skip to content
next

Next.js: Redirect from / to another page

Sep 14, 2024Abhishek EH2 Min Read
Next.js: Redirect from / to another page

You might have a scenario where you don't want to show the / route and by default redirect it to some route like /dashboard. In this article, we will explore different ways to achieve the same.

Using next.config.mjs

If you want to redirect the user even before the / page is loaded, you can use the following configuration in the next.config.mjs file:

next.config.mjs
1/** @type {import('next').NextConfig} */
2const nextConfig = {
3 async redirects() {
4 return [
5 {
6 source: '/',
7 destination: '/dashboard',
8 permanent: true,
9 },
10 ];
11 },
12 // rest of the config
13};
14
15export default nextConfig;

The flag permanent: true makes the redirection HTTP status code as 308, which tells the search engines that this is a permanent redirect and no need to index / page.

Using useEffect or Event handlers

If you don't want to use the Next.js config, and want to redirect after page load or any event, you can use the useRouter hook:

1"use client";
2
3import { useRouter } from "next/navigation";
4import { useEffect } from "react";
5
6export default function RedirectToDashboard() {
7 const router = useRouter();
8 useEffect(() => {
9 router.push("/dashboard");
10 }, [router]);
11}

You can call the router.push() function inside any even handlers as well.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com