Next.js - redirect() Function



The redirect() Function

The Next.js redirect() function is used to redirect the user to another URL. You can use the redirect() function in Server Components, Route Handlers, and Server Actions.

Syntax

Following is the syntax of the redirect() function.

async redirects() {
    return [
        {
            source: "",        // The path redirect from
            destination: "",   // The path redirect to
            permanent: ,       // Set to true if permanent redirect
        }
    ];
},

Parameters

The redirect() function accepts two arguments.

  • path - string - The URL to redirect to. Can be a relative or absolute path.
  • type - 'replace' (default) or 'push' - The type of redirect to perform.

By default, redirect will use push (adding a new entry to the browser history stack) in Server Actions and replace (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the type parameter. The type parameter has no effect when used in Server Components.

Return Value

The redirect() function returns an object specifying source of redirection, destination of redirection and redirecting nature.

Example 1

You can use the redirects option in the next.config.js file to redirect an incoming request path to a different destination path. 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",        
            destination: "/about",   
            permanent: true,     
          }
        ];
      },
};

export default nextConfig;

Output

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

next.js-redirecting-in-config-file

Example 2

The redirect() function can be used in a Client Component through a Server Action. If you need to use an event handler to redirect the user, you can use the useRouter hook. In the code below, we defined two functions, one is ClientRedirect which is used to redirect the user to the post page and the other is navigate which is used to redirect the user to the post page.

// app/client-redirects.tsx

'use client'
 
import { navigate } from './actions'
 
export function ClientRedirect() {
  return (
    <form action={navigate}>
        <input type="text" name="id" />
        <button>Submit</button>
    </form>
  )
}

// app/actions.ts

'use server'
 
import { redirect } from 'next/navigation'
 
export async function navigate(data: FormData) {
  redirect(`/posts/${data.get('id')}`)
}
Advertisements