skip to Main Content

In SSR when I am using Next.js App Router, How can I get full URL of the current page?

I cannot use window.location.href as window is not defined and with useRouter() I cannot get full URL

2

Answers


  1. You can use next/headers to retrieve the full headers, and then use it to construct the full url.

    import { headers } from 'next/headers';
    
    export default function ServerComponent() {
        const fullUrl = headers().get('referer');
    
        console.log(fullUrl);
    }
    

    Or you can use headers like host, x-forwarded-host and x-invoke-path (depending on which headers are set in your case).

    Login or Signup to reply.
  2. You are absolutely right, since there is no window object in SSR
    window.location.href can’t be used and useRouter() hook is available on the client side only. However with useRouter hook you can get the current path name in the SSR

    Potential Solution

    install the package npm install nextjs-current-url

    you can use the getURL function from nextjs-current-url package. It takes req object as input that is available in the getServerSideProps.

    export async function getServerSideProps(context) {
      const { req } = context;
      const the_url = await getUrl({ req });
    
      return {
        props: {
          the_url,
        },
      };
    }
    

    Usage in your component

    const YourComponent = ({ the_url }) => {
      return (
        <div>
          <h1>{the_url}</h1>
        </div>
      );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search