Education
Developer Advocate
Last updated on Nov 28, 2024
Last updated on Nov 29, 2024
When building a Next.js app, one of the common tasks developers face is determining the current URL domain. Whether you need this information for analytics, dynamic rendering, or creating SEO-friendly meta tags, understanding how to access the current path or full domain dynamically is crucial.
This blog explains step-by-step how to fetch the current URL in Next.js using both server components and client components, ensuring your approach fits the context of your application.
Fetching the current URL is vital in scenarios where your Next.js app needs to:
• Generate dynamic meta tags for SEO.
• Redirect users based on their current path or hostname.
• Dynamically load content based on the protocol, domain, or route.
• Integrate with third-party APIs requiring the full URL.
In Next.js, this can be achieved using both client components and server components, depending on where you need the data.
Before diving into code, let’s clarify where and how you can access the current URL:
Client Side: On the client side, you can use the window object to fetch the location details. However, client components are required to access browser-specific APIs like the window object.
Server Side: On the server, you don’t have access to the window object, but you can extract the hostname and protocol from the headers or context during the request lifecycle.
To fetch the current URL on the client side, you’ll rely on the window object. Since accessing window is specific to the browser, you must ensure the code runs in a client component.
1"use client"; 2 3import { useEffect, useState } from "react"; 4 5export default function CurrentURL() { 6 const [currentUrl, setCurrentUrl] = useState(""); 7 8 useEffect(() => { 9 if (typeof window !== "undefined") { 10 // Access the current URL using the window object 11 setCurrentUrl(window.location.href); 12 } 13 }, []); 14 15 return ( 16 <div> 17 <h1>Current URL</h1> 18 <p>{currentUrl ? `The current URL is: ${currentUrl}` : "Loading..."}</p> 19 </div> 20 ); 21}
• Use typeof window to ensure safe access to the window object.
• Wrap the logic in a useEffect hook to prevent server-side execution.
In server components, the window object is not available, but you can fetch the current URL using the headers object from the request.
1export default async function ServerURL({ headers }) { 2 const host = headers["x-forwarded-host"] || headers.host; 3 const protocol = headers["x-forwarded-proto"] || "https"; 4 5 const fullUrl = `${protocol}://${host}`; 6 7 return ( 8 <div> 9 <h1>Server-Side Current URL</h1> 10 <p>The full URL is: {fullUrl}</p> 11 </div> 12 ); 13}
• Use the x-forwarded-host and x-forwarded-proto headers to fetch the hostname and protocol.
• This approach is ideal for SSR (Server-Side Rendering) and API routes.
For apps built using the pages directory, you can utilize the next/router library to get the current path and query parameters.
1import { useRouter } from "next/router"; 2 3export default function CurrentPath() { 4 const router = useRouter(); 5 6 return ( 7 <div> 8 <h1>Current Path</h1> 9 <p>The current path is: {router.pathname}</p> 10 <p>Full URL: {router.asPath}</p> 11 </div> 12 ); 13}
• The useRouter hook provides the pathname and asPath properties.
• Ideal for routing and working within the pages directory.
If you frequently need to get the current URL, a helper function can streamline your code. Here’s how you can create one:
1export function getCurrentUrl(headers) { 2 const protocol = headers["x-forwarded-proto"] || "https"; 3 const host = headers["x-forwarded-host"] || headers.host; 4 5 return `${protocol}://${host}`; 6}
1import { getCurrentUrl } from "./helpers"; 2 3export default function ServerSideExample({ headers }) { 4 const fullUrl = getCurrentUrl(headers); 5 6 return <p>The full server URL is: {fullUrl}</p>; 7}
Accessing window on the server: If you attempt to access window in a server component, you'll encounter an error since the window object is undefined on the server.
Undefined Headers: Always ensure headers are properly passed when working on the server. Missing headers can lead to incomplete URLs.
Default Protocol Assumption: Ensure you handle cases where the protocol is not defined in the headers, defaulting to https when necessary.
Fetching the current URL domain in a Next.js app requires understanding the context (client vs. server) and the tools available, such as the window object, next/router, and request headers. By using client components for client-side operations and server components for server-side rendering, you can handle dynamic URLs efficiently.
Whether you need the current path for routing, the full URL for analytics, or the hostname for API requests, Next.js provides robust mechanisms to achieve your goals. Mastering this will enhance your Next.js app's performance, SEO, and user experience.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.