Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return window.location.host on a static next.js site?

I would like to return {window.location.host} on a static next.js website

I managed to log the value but I can not figure out how to return it.

import React from "react";
import { useEffect } from "react";

export default function Test() {
  useEffect(() => {
    console.log(window.location.host);
  }, []);

  return <h1>{window.location.host}</h1>;
}

I’m a JS beginner, all I managed was to return it once on the initial page load with useEffect but after a reload it gives the error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ReferenceError: window is not defined

>Solution :

window is unavailable during server side rendering, you can a state hook and update it in your effect hook client side.

import {useEffect, useState} from "react";

export default function TestPage() {
  const [host, setHost] = useState("");
  useEffect(() => {
    if (typeof window !== "undefined") setHost(window.location.host);
  }, []);
  return <h1>{host}</h1>;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading