next js back to previous page

To go back to the previous page in Next.js, you can use the Router object provided by the next/router module. The Router object allows you to programmatically navigate between pages in your Next.js application. Here are the steps to go back to the previous page:

  1. Import the Router object from the next/router module at the top of your file:
import { useRouter } from 'next/router';
  1. Inside your component, you can access the Router object using the useRouter hook:
const router = useRouter();
  1. To go back to the previous page, you can use the back method of the Router object:
router.back();
  1. Optionally, you can wrap the router.back() call inside an event handler or a function to trigger the navigation on a specific action, such as a button click:
const handleGoBack = () => {
  router.back();
};

<button onClick={handleGoBack}>Go Back</button>

That's it! When the router.back() method is called, Next.js will navigate the user back to the previous page in the browser's history.

Remember to import the necessary modules and hooks, and use the useRouter hook to access the Router object. Then, you can use the back method of the Router object to navigate back to the previous page.