Table of Contents
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.
next.config.mjs
Using 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:
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 config13};1415export 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";23import { useRouter } from "next/navigation";4import { useEffect } from "react";56export 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.
If you have liked article, stay in touch with me by following me on twitter.
Leave a Comment