Next.js Discord

Discord Forum

How to get page URL or hostname in NextJs Project?

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
I want to get the hostname in my Next.js app and use it in both server and client components. I tried the following code:
import { headers } from "next/headers"; export async function getHostUrl() { // Client-side if (typeof window !== "undefined") { return window.location.host; } else { // Server-side const headersList = headers(); const host = headersList.get("host"); return https://${host}; } }
It works perfectly in server components because it uses the headers() API for the server-side logic. However, when I try to use it in a client component, I get an error like this:

How can I modify this function to make it usable in both server and client components?"
Image

7 Replies

Avatar
Asian black bearOP
so i have to create two files ,right ?
Avatar
@Asian black bear so i have to create two files ,right ?
Avatar
yes, you can also create 2 extra files and there two extra functions (wrapper) that just returns those function. In my opinion there is no need to create 2 extra functions for those 2 functions. Normally that leads to errors when your project is unnecessary complex
Avatar
the error says pages/ dir, which means server component doesnt exist for you

you have to use app dir for server components
Avatar
Asian black bearOP
i tried this solution :
// src/utils/getHostUrl.ts import { useEffect, useState } from 'react'; async function getServerUrl() { // Server-side const { headers } = await import("next/headers"); const headersList = await headers(); const host = headersList.get("host"); return "https://" + host?.toString(); } function useClientUrl() { // Client-side const [currentUrl, setCurrentUrl] = useState<string | null>(null); useEffect(() => { setCurrentUrl(window.location.href); }, []); return currentUrl ? new URL(currentUrl) : null; } export { getServerUrl, useClientUrl };
could you rate it please