Open In App

Go Back to the Previous Page in Nextjs

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In NextJS, we can navigate back to previous page with the help of useRouter hook from the next router. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about how to go back to te previous page in next.js.

Prerequisites:

Approach

To go back to the previous page in Next.js, you can use the useRouter hook from 'next/router'. It provides a back() method that uses the browser's history, similar to how you'd navigate using the back button. Testing ensures it works smoothly with the browser's history stack.

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command and answer a few questions.

npx create-next-app@latest app_name

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?  ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

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

cd app_name

Project Structure:

previous-page-structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "react": "^18",
    "react-dom": "^18",
    "next": "14.2.3"
},
"devDependencies": {
    "postcss": "^8",
    "tailwindcss": "^3.4.1"
}

Example: Implementation to show Go back to the previous page in NextJS.

JavaScript
//File path: src/app/page.js

import Link from "next/link";

export default function Home() {
    return (
        <>
            <h2>
                Go back to the
                previous page | GeeksForGeeks
            </h2>
            <Link href={"/about"} >
                About Page
            </Link>
        </>
    );
}
JavaScript
//File path: src/app/about/page.js

'use client';
import { useRouter } from "next/navigation";

export default function Page() {
    const router = useRouter()

    function previous() {
        window.history.back()
    }
    return (
        <>
            <span>Using useRouter() hook </span>
            <button onClick={
                () => router.back()}>Back</button>
            <hr />
            <span>
                Using JavaScript History API
            </span>
            <button onClick={previous}>
                Back
            </button>
        </>
    );
}

Step to Run Application: Run the application using the following command from the root directory of the project

npm run dev

Output: Your project will be shown in the URL http://localhost:3000/


Similar Reads