Explain Codes LogoExplain Codes Logo

How to get the previous URL in JavaScript?

javascript
prompt-engineering
history-api
state-management
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Fetch the prior URL using the document.referrer method:

console.log(document.referrer); // Prints the referrer URL if there is one.

The returned string is empty if no referrer is available or due to privacy policies.

Understanding the value of document.referrer

While using document.referrer seems simple, its value may not always be reliable. Cross-domain navigations, direct URL entries, and bookmarks won't generate any referrer. However, within site navigation, it works well for providing the URL of the page visited before the current one.

Overcoming limitations of document.referrer

Ways to track the previous URL

When document.referrer proves inadequate, consider these methods:

  1. URL parameters: Use query strings to include a previous page indicator when navigating.
  2. Cookies: Store the current URL before navigating, to be referred to as the "previous" URL on the next load.
  3. Session Storage: Think about using sessionStorage or localStorage for better state management.
  4. Server-side sessions: Keep the prior URL in your server's session state, ready for retrieval during the next request.

Working with the window.history object

The History API provides history.pushState, history.back(), history.forward(), and history.go() to adjust and navigate the browser history. However, take note that these methods don't return the previous URL; they navigate to it instead.

Caveats and implications

Privacy matters

Remember to always place user privacy at the forefront when you're trying to track navigation histories. Always seek user consent if you're storing their navigational data through cookies or similar methods.

Security hazards

Avoiding cross-site scripting (XSS) vulnerabilities when processing URLs is vital. Sanitise any information if you plan to display it or use it for further processing.

Known limitations and inconsistencies

Intra-frame navigation

document.referrer can behave unpredictably with iframes or framesets. Each frame may retain its own referrer information, which could be inconsistent with the top-level document's URL.

Browser incoherence

Some browsers and configurations may modify or omit referrer information, so cross-browser testing and being aware of privacy settings is paramount.

Making use of the HTML5 History API

Applying pushState for SPAs

Single-Page Applications (SPAs) often leverage history.pushState and window.history.state to manage state transitions smoothly without page reloads. This can also store the previous URL in a state object:

// Because even URLs need a time machine! 🕰️ history.pushState({ prevUrl: window.location.href }, null, newUrl);

Compatibility matters

Always check browser compatibility for pushState and related functions as older browsers might not support these features.