🐶
Next.js

Get Page URL or Hostname in Next.js

By Filip on 10/05/2024

Learn how to easily access and utilize the current page URL and hostname within your Next.js project for dynamic routing, SEO optimization, and more.

Get Page URL or Hostname in Next.js

Table of Contents

Introduction

In Next.js, there are different ways to get the current URL depending on whether you're on the client-side or server-side. This guide will explain the various methods and when to use them.

Step-by-Step Guide

Next.js offers various methods to access the current URL depending on your specific needs and the context (client-side or server-side). Here's a breakdown of different approaches:

Client-Side Rendering (CSR):

  1. Using window.location:

    • This is the most straightforward way to get the complete URL information on the client-side.
    • Important: Ensure you access window.location only after the component mounts, as it's not available during server-side rendering.
    import { useEffect, useState } from 'react';
    
    function MyComponent() {
      const [url, setUrl] = useState('');
    
      useEffect(() => {
        setUrl(window.location.href); // Get the full URL
        // You can also access specific parts like hostname, pathname, etc.
      }, []);
    
      return <div>The current URL is: {url}</div>;
    }
  2. Using the useRouter Hook (Next.js Specific):

    • This hook from Next.js provides access to routing information within your components.
    import { useRouter } from 'next/router';
    
    function MyComponent() {
      const router = useRouter();
      const currentPath = router.pathname; // Get the current route path
      const currentQuery = router.query; // Get query parameters as an object
    
      return (
        <div>
          Current path: {currentPath}
          <br />
          Query parameters: {JSON.stringify(currentQuery)}
        </div>
      );
    }

Server-Side Rendering (SSR) and API Routes:

  1. Using NextApiRequest Object:

    • In API routes or during server-side rendering, you can access the request object (req) which contains URL information.
    export default function handler(req, res) {
      const url = req.url; // Get the full URL
      const host = req.headers.host; // Get the hostname
    
      // ... your logic
    }
  2. Using usePathname Hook (Next.js 13 App Router):

    • In Next.js 13's App Router, you can use the usePathname hook to access the current route's pathname.
    import { usePathname } from 'next/navigation';
    
    function MyComponent() {
      const pathname = usePathname();
    
      return <div>The current pathname is: {pathname}</div>;
    }

Additional Considerations:

  • Dynamic Routes: If you're using dynamic routes with Next.js, you can access the dynamic segments within the URL using the useRouter hook or the req.query object.
  • Custom Servers: When using a custom server, you might need to configure it to handle URL parsing and routing depending on your setup.

Choosing the Right Method:

  • For client-side access to the full URL, use window.location.
  • For accessing routing information within components, use the useRouter hook.
  • In API routes or server-side rendering, use the NextApiRequest object.
  • In Next.js 13's App Router, use the usePathname hook for the current route's pathname.

Remember to choose the method that best suits your specific use case and context within your Next.js application.

Code Example

This code provides various methods to get the current URL in a Next.js application, covering both client-side rendering (CSR) and server-side rendering (SSR) scenarios. For CSR, it demonstrates using window.location to access the full URL and its components, as well as using the useRouter hook from Next.js to get the current path and query parameters. For SSR and API routes, it shows how to utilize the NextApiRequest object to retrieve the URL and hostname. Additionally, it introduces the usePathname hook (available in Next.js 13) as another way to get the current pathname. The code emphasizes choosing the appropriate method based on the context and highlights important considerations such as accessing window.location after component mount and handling dynamic routes.

Following your provided guide, here are the JavaScript examples for each method:

Client-Side Rendering (CSR):

1. Using window.location:

import { useEffect, useState } from 'react';

function MyComponent() {
  const [url, setUrl] = useState('');

  useEffect(() => {
    setUrl(window.location.href); // Get the full URL
    // You can also access specific parts like:
    // window.location.hostname // Hostname
    // window.location.pathname // Path
    // window.location.search // Query string
  }, []);

  return <div>The current URL is: {url}</div>;
}

2. Using the useRouter Hook:

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();
  const currentPath = router.pathname;
  const currentQuery = router.query;

  return (
    <div>
      Current path: {currentPath}
      <br />
      Query parameters: {JSON.stringify(currentQuery)}
    </div>
  );
}

Server-Side Rendering (SSR) and API Routes:

1. Using NextApiRequest Object:

export default function handler(req, res) {
  const url = req.url; // Get the full URL
  const host = req.headers.host; // Get the hostname

  // ... your logic to handle the request
}

2. Using usePathname Hook (Next.js 13):

import { usePathname } from 'next/navigation';

function MyComponent() {
  const pathname = usePathname();

  return <div>The current pathname is: {pathname}</div>;
}

Remember:

  • Choose the method that best suits your needs and context.
  • For client-side, ensure window.location is accessed after component mounts.
  • For dynamic routes, use useRouter or req.query to access segments.
  • Consider custom server configurations for URL parsing if needed.

Additional Notes

Dynamic Routes and URL Parameters:

  • Accessing Dynamic Segments: When using dynamic routes (e.g., /blog/[slug]), you can access the dynamic segments of the URL using the useRouter hook:
const router = useRouter();
const { slug } = router.query; // Access the 'slug' parameter
  • Handling Optional Catch-All Routes: For optional catch-all routes (e.g., /blog/[...slug]), the slug parameter will be an array containing all segments after /blog/.

Edge Cases and Considerations:

  • Client-Side Navigation and URL Updates: If you're using client-side routing libraries or custom navigation logic, ensure that the URL is updated accordingly to reflect the current state of the application.
  • Server-Side Redirects: When performing server-side redirects, you can use the NextResponse object to set the destination URL and status code.
  • URL Encoding and Decoding: Be mindful of URL encoding and decoding when working with special characters or user-generated content in URLs.

Advanced Use Cases:

  • Custom Routing Solutions: For complex routing scenarios, you might consider using third-party routing libraries or building your own custom routing solution.
  • URL Parsing and Manipulation: Libraries like path-to-regexp or query-string can provide more advanced URL parsing and manipulation capabilities.

Security Best Practices:

  • Validate and Sanitize User Input: Always validate and sanitize any user input that is used to construct URLs to prevent security vulnerabilities like cross-site scripting (XSS).
  • Avoid Exposing Sensitive Information: Be cautious about exposing sensitive information in URLs, especially when dealing with authentication or authorization.

Summary

Context Method Description
Client-side Rendering window.location Provides complete URL information after component mounts.
Client-side Rendering useRouter hook (Next.js) Offers access to routing details like path and query parameters.
Server-side Rendering NextApiRequest object Exposes URL details within API routes or during server-side rendering.
Next.js 13 App Router usePathname hook (Next.js 13) Retrieves the current route's pathname within the App Router context.
Dynamic Routes useRouter hook or req.query object Allows access to dynamic segments within the URL.
Custom Servers Server-specific configuration May require setup for URL parsing and routing depending on the server used.

Conclusion

By understanding these methods and considerations, you can effectively work with URLs in your Next.js applications, ensuring smooth navigation, data fetching, and a seamless user experience. Remember to choose the approach that aligns best with your specific use case and the context of your application.

References

Were You Able to Follow the Instructions?

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