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.


# development

# production
# we use the prefix NEXT_PUBLIC so that it can be found on the browser

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();

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 (
      <p>This is a static page</p>
      <Link href={getURL("/hello")}>hello</Link>
export default StaticPage ;

That's basically it!



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

Share this post!

Related Posts


Subscribe to our newsletter

Get up-to-date on latest articles on react.js, node.js, graphql, full-stack web development. No Spam. Helpful articles to improve your skills. Sent directly to your inbox.