How to get previous url in nextjs

To get the previous URL in Next.js, you can make use of the useRouter hook provided by the next/router package. Here are the steps to achieve this:

  1. Import the necessary dependencies:
import { useRouter } from 'next/router';
  1. Inside your functional component, initialize the router object using the useRouter hook:
const router = useRouter();
  1. Use the router object to access the asPath property, which represents the current URL path, including query parameters. This will give you the previous URL:
const previousUrl = router.asPath;

Now, you can use the previousUrl variable to access the previous URL in your Next.js application.

Here is the complete code snippet:

import { useRouter } from 'next/router';

const MyComponent = () => {
  const router = useRouter();
  const previousUrl = router.asPath;

  // Rest of your component code

  return (
    // JSX code
  );
};

export default MyComponent;

By following these steps, you should be able to retrieve the previous URL in Next.js using the next/router package and the useRouter hook.