ReactHustle

How to Get The Current URL Domain in NextJS Server-Side and Client-Side

Jasser Mark Arioste

Jasser Mark Arioste

How to Get The Current URL Domain in NextJS Server-Side and Client-Side

Hello, hustlers! In this tutorial, you'll learn how to get the current URL inside a react component for both server-side and client-side rendering. 

Getting the Current Domain URL #

Perhaps, you've already run into the problem where you get the current URL using window.location.href in a React Component but then get the error `ReferenceError: window is not defined`. This happens because NextJS will generate the pages from the server-side first.

The Solution #

To get the current URL from the server-side, we must first know the origin or the site domain. Now, if your site is deployed in Vercel, they automatically provide the environment variable VERCEL_URL. The VERCEL_URL will have a value of something like xxx.vercel.app however, almost every site uses a custom domain like this website reacthustle.com. We can't really use this environment variable for production.

So to solve this, there are two steps.

First, we have to provide our own environment variable, something like NEXT_PUBLIC_SITE_URL.

#.env

# development
NEXT_PUBLIC_SITE_URL=http://localhost:3000

# production
NEXT_PUBLIC_SITE_URL=https://yourdomain.com
# we use the prefix NEXT_PUBLIC so that it can be found on the browser
12345678

Next, we create a utility function to get the current URL:

// utils/getURL.ts
const IS_SERVER = typeof window === "undefined";
export default function getURL(path: string) {
  const baseURL = IS_SERVER
    ? process.env.NEXT_PUBLIC_SITE_URL!
    : window.location.origin;
  return new URL(path, baseURL).toString();
}
12345678

Now, you can use this to get the full absolute URL from anywhere in the application. 

import Link from "next/link";
import getURL from "../utils/getURL";

const StaticPage = () => {
  return (
    <div>
      <p>This is a static page</p>
      <Link href={getURL("/hello")}>hello</Link>
    </div>
  );
};
export default StaticPage ;
123456789101112

That's basically it!

Resources #

Credits: Image by Александр Пургин from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle