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:
- Import the necessary dependencies:
import { useRouter } from 'next/router';
- Inside your functional component, initialize the
router
object using theuseRouter
hook:
const router = useRouter();
- Use the
router
object to access theasPath
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.