Next.js Discord

Discord Forum

Get Subdomain (hostname) from within client component

Unanswered
Flemish Giant posted this in #help-forum
Open in Discord
Flemish GiantOP
I have client component which should identify the subdomain currently in browser.

I'm struggling to get this to work. My currnt attmpt looks like the below:

 const [subdomain, setSubdomain] = useState<string | null>(null);

  useEffect(() => {
    const getSubdomain = () => {
      const { hostname } = window.location;
      const parts = hostname.split(".");
      if (parts.length >= 3) {
        return parts[0]; // Assuming the subdomain is the first part
      }
      return null;
    };
    setSubdomain(getSubdomain());
  }, []);

  console.log("subdomain:" + subdomain);


However the state doesn't get set and the console.log is always null.

This has "use client" at the top of the component.

any ideas?

8 Replies