Open In App

Next.js Functions: redirect

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is redirect Function. In this article, we will learn about redirect Function.

The redirect function in Next.js is used to redirect users from one URL to another. It can be used in various contexts such as Server Components, Client Components, Route Handlers and Server Actions. permanentRedirect can either insert a meta tag for client-side redirection or serve an appropriate HTTP redirect status code response.

Syntax:

import { redirect } from 'next/navigation';

// Usage
redirect(path, type);

Where:

  • path(string): It is a path where we are redirecting the user. it can be relative or absolute path.
  • type: It is used to give type of redirect. the value can be a "replace" or "push". replace, It replaces the current URL in the browser history stack. push, It adds a new entry to the browser history stack.

Steps to Create Next.js Application

Step 1: Create a Next.js application using the following command.

npx create-next-app@latest gfg

Step 2: It will ask you some questions, so choose as the following.

Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... No
√ Would you like to customize the default import alias (@/*)? ... Yes

Step 3: After creating your project folder i.e. gfg, move to it using the following command.

cd gfg

Project Structure:

permanent-redirect-structure
Project structure

Example: The below example demonstrate the use of redirect function in next.js.

JavaScript
// File path: src/app/page.js
"use client";
import {redirect, useRouter} from "next/navigation";

export default function Home()
{

    const router = useRouter();

    const isRedirect = true
    if (!isRedirect)
    {
        redirect("/profile")
    }

  return (
    <>
      <h1>GeeksForGeeks | Next.js Redirect Function</h1>
      <button onClick={() => router.push('/profile')}>Profile Page</button>
    </>
  );
}
JavaScript
// File path: src/app/profile/page.js
"use client";
import {useRouter} from "next/navigation"

export default function Profile()
{

    const router = useRouter()

    return (
        <>
            <h1>Profile Page</h1>
            <button onClick={() => router.back()}>
               Back to previous page
            </button>
        </>
    )
}

To run the Application open the terminal in the project folder and enter the following command:

npm run dev

Output:


Next Article

Similar Reads