Next.js - Redirecting Routes



Next.js provide inbuilt methods and APIs for handling redirecting of routes in application. This is very useful when we want the user to redirect to an actual page if they are visiting a broken or incorrect page. In this chapter we will learn how to implement redirecting of external routes, conditional redirecting and client side redirecting in Next.js application

Methods for Redirecting in Next.js

Following are three methods to implement redirecting in Next.js.

Methods Purpose Used at
useRouter hook Used to perform client side navigation and redirecting. Client side components
redirect() method Redirects external or internal requests to any of the routes in application. next.config.js file
NextResponse.redirect Redirect an incoming request based on a condition Middleware

Redirecting in Next.js using redirect() method

The redirects option in the next.config.js file allows you to redirect an incoming request path to a different destination path. This is useful when you change the URL structure of pages or have a list of redirects that are known ahead of time.

Example

In this example, the route "/abouttt" will be redirected to "/about" page. This will useful when user make error in typing URL.

// ./next.config.ts file

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
    async redirects() {
        return [
          {
            source: "/abouttt",        // The path redirect from
            destination: "/about",     // The path redirect to
            permanent: true,           // Permanent redirecting
          }
        ];
      },
};

export default nextConfig;

Output

In the output below, you can see that /abouttt is redirected to /about

next.js-redirecting-in-config-file

Redirecting in Next.js Using useRoute hook

In Next.js, useRoute hook is used to redirect or navigate routes at client side. This hook can only be used in client side components. This is useful when we want redirect user to home page or any other page after clicking a button or submitting a form.

Example

In the example below, we implemented a product ordering feature to the product page we created in the previous chapters. On clicking the button, user will get a confirmation of the order and redirect them to home page using 'useRoute' hook.

"use client"; 

import { useRouter } from "next/navigation";
import { PageProps } from "next/dist/shared/lib/router/utils/page-props";

export default function ProductPage({ params }: PageProps) {
    const router = useRouter();

    const handleClick = () =>{
        alert("Order Placed...");

        // Navigate to home page after placing order
        router.push("/");
    };
    return (
        <div>
        <h1>Product {params.id}</h1>
        <p>This is the product page for item {params.id}</p>
        <button onClick={handleClick}>Order Item</button>
        </div>
    );
}

Output

In the output, after placing order user is getting redirected to home page.

next.js-navigating-dynamically

Redirect in Next.js Using Middleware

Middleware allows you to run a code before a request is completed. Then, based on the incoming request, redirect to a different URL using NextResponse.redirect. This is useful if you want to redirect users based on a condition (e.g. authentication, session management, etc) or have a large number of redirects.

Example

In the example below, we will redirect the user to a /login page if they are not authenticated.

import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
 
export function middleware(request: NextRequest) {
  const isAuthenticated = authenticate(request)
 
  // If the user is authenticated, continue as normal
  if (isAuthenticated) {
    return NextResponse.next()
  }
 
  // Redirect to login page if not authenticated
  return NextResponse.redirect(new URL('/login', request.url))
}
 
export const config = {
  matcher: '/dashboard/:path*',
}
Advertisements