How to Get The Current URL Domain in NextJS Server-Side and Client-Side
Jasser Mark Arioste
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