In Next.js, retrieving the URL of the previous page is typically done via the Referer HTTP header. The Referer header is automatically set by the browser when a user navigates from one page to another, indicating the origin of the request.
Here is a practical example demonstrating how to retrieve the Referer header in Next.js pages or API routes:
Step 1: Create an API Route
In a Next.js project, you can create a new API file in the pages/api directory. For example, create a file named referer.js:
js// pages/api/referer.js export default function handler(req, res) { const referer = req.headers['referer'] || 'Direct visit without referer'; res.status(200).json({ referer }); }
This API route checks the Referer header from the client request and returns it to the client. If the Referer header is missing, it defaults to a direct visit.
Step 2: Call the API in a Page
You can call this API in any page component to retrieve the Referer header. For example, in the pages/index.js file:
jsx// pages/index.js import { useEffect, useState } from 'react'; function HomePage() { const [referer, setReferer] = useState(''); useEffect(() => { async function fetchReferer() { const response = await fetch('/api/referer'); const data = await response.json(); setReferer(data.referer); } fetchReferer(); }, []); return ( <div> <h1>Welcome to the homepage!</h1> <p>The referer URL is: {referer}</p> </div> ); } export default HomePage;
In this example, the page fetches the /api/referer API upon loading and displays the source page.
Notes
- Note that the
Refererheader can be modified or deleted by users or certain browser extensions, so it should not be relied upon for important security decisions. - This method is primarily used for tracking and logging purposes.
Using the above method, you should be able to effectively retrieve and utilize the URL of the previous page in a Next.js application.