🐶
Next.js

Next.js Get Previous URL: A Simple Guide

By Filip on 10/05/2024

Learn how to access the previous URL in your Next.js application for seamless user navigation.

Next.js Get Previous URL: A Simple Guide

Table of Contents

Introduction

In Next.js, obtaining the previous URL is not straightforward due to its single-page application nature. This article provides solutions to achieve this, including a custom hook using useRouter and useState for manual tracking, and the Browser History API for limited cases. It also highlights important considerations for state management and server-side rendering.

Step-by-Step Guide

Here's how to get the previous URL in Next.js, combining insights from the provided resources:

Understanding the Challenge

Next.js doesn't inherently store the "previous URL" in its router. This is because Next.js focuses on single-page application (SPA) behavior, where navigation is managed within the app itself.

Solutions

  1. Manual Tracking with useRouter and State:

    • Import useRouter and useState:

      import { useRouter } from 'next/router';
      import { useState, useEffect } from 'react';
    • Create a custom hook:

      function usePreviousUrl() {
        const router = useRouter();
        const [previousUrl, setPreviousUrl] = useState(null);
      
        useEffect(() => {
          const handleRouteChange = (url) => {
            setPreviousUrl(router.asPath); 
          };
      
          router.events.on('routeChangeStart', handleRouteChange);
      
          return () => {
            router.events.off('routeChangeStart', handleRouteChange);
          };
        }, [router]);
      
        return previousUrl;
      }
    • Use the hook in your component:

      function MyComponent() {
        const previousUrl = usePreviousUrl();
      
        return (
          <div>
            {previousUrl && <p>You came from: {previousUrl}</p>}
            {/* ... rest of your component */}
          </div>
        );
      }
  2. Browser History API (Limited):

    • Direct Access (unreliable in SPAs):

      const previousUrl = document.referrer; 
      • Caution: This often doesn't work as expected in SPAs because the browser might not update the referrer for internal navigation.
    • History Manipulation (for simple cases):

      function goBack() {
        window.history.back(); 
      }
      • Use Case: This is suitable if you just want a "Back" button functionality.

Important Considerations:

  • State Management: For more complex scenarios (e.g., tracking a history of URLs), consider a state management library like Redux or Zustand.
  • Server-Side Rendering (SSR): If you need the previous URL on the server during SSR, you'll need to implement a solution that works in both server and client environments.

Let me know if you have any other questions.

Code Example

This JavaScript code defines a custom React hook usePreviousUrl that keeps track of the URL the user was on before navigating to the current page. It uses the next/router to listen for route changes and updates the previous URL in a state variable. The MyComponent demonstrates how to use this hook to display the previous URL to the user.

import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';

function usePreviousUrl() {
  const router = useRouter();
  const [previousUrl, setPreviousUrl] = useState(null);

  useEffect(() => {
    const handleRouteChange = (url) => {
      setPreviousUrl(router.asPath); 
    };

    router.events.on('routeChangeStart', handleRouteChange);

    return () => {
      router.events.off('routeChangeStart', handleRouteChange);
    };
  }, [router]);

  return previousUrl;
}

function MyComponent() {
  const previousUrl = usePreviousUrl();

  return (
    <div>
      {previousUrl && <p>You came from: {previousUrl}</p>}
      {/* ... rest of your component */}
    </div>
  );
}

export default MyComponent;

Explanation:

  1. usePreviousUrl Hook:

    • This hook uses the useRouter hook from Next.js to access the router object.
    • It initializes a state variable previousUrl with useState(null).
    • The useEffect hook sets up an event listener (routeChangeStart) on the router.
    • Whenever the route is about to change, the handleRouteChange function updates the previousUrl state with the current router.asPath (the current URL).
    • The cleanup function in useEffect removes the event listener when the component unmounts.
  2. MyComponent:

    • This component calls the usePreviousUrl hook to get the previous URL.
    • It conditionally renders a paragraph displaying the previous URL if it exists.

How it Works:

  • When a user navigates to MyComponent, the previousUrl will be null initially.
  • As soon as the user navigates to a different route within your Next.js application, the routeChangeStart event is triggered.
  • The handleRouteChange function updates the previousUrl state with the URL of the page the user was on before the navigation.
  • The MyComponent re-renders, and the previous URL is displayed.

Additional Notes

  • Simplicity vs. Robustness: The usePreviousUrl hook provides a simple solution for most cases. However, for complex applications with deep navigation history or the need for persistence across sessions, a more robust state management solution is recommended.
  • Alternative Event: Instead of routeChangeStart, you could use the routeChangeComplete event to capture the previous URL after the navigation is complete. This might be preferable if you need to perform actions based on the previous URL after the new page has loaded.
  • Initial Value: The usePreviousUrl hook starts with previousUrl as null. You can initialize it with a default value or fetch the initial previous URL from a different source (e.g., local storage) if needed.
  • Edge Cases: Be aware of edge cases like browser refresh or direct page loads. In these scenarios, the previous URL might not be available or might not be what you expect.
  • Security: If you're using the previous URL for sensitive operations, ensure you validate and sanitize it properly to prevent potential security vulnerabilities.

Summary

Method Description Considerations
Manual Tracking with useRouter and State Utilizes Next.js's useRouter hook and React's useState hook to store the previous URL in a state variable. Suitable for most SPA use cases. Can be integrated with state management libraries for more complex scenarios.
Browser History API (Limited) Leverages the browser's built-in history functionality. * Direct Access: Often unreliable in SPAs. * History Manipulation: Suitable for simple "Back" button functionality.

Conclusion

Choosing the best method for accessing the previous URL in your Next.js application depends on your specific needs and the complexity of your project. While the Browser History API offers a simple solution for basic "Back" button functionality, manual tracking with useRouter and state provides greater flexibility and control, especially when integrated with state management libraries for more complex scenarios. Consider the trade-offs between simplicity and robustness, and carefully evaluate your application's requirements to select the most appropriate approach for managing the previous URL effectively.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait