Problem encountered during NextJS build: ReferenceError - 'window' is undefined

While I am in the process of developing my app, I have encountered a perplexing issue with a

ReferenceError: window is not defined
. This error seems to be happening even though I am utilizing 'use client'

"use client";
import React, { useEffect, useState } from "react";
import { ref, getDownloadURL } from "firebase/storage";
import { storage } from "./firebase"; // Adjust the import path as needed
import Image from "next/image";

const Hero = () => {
    const [bgImageUrl, setBgImageUrl] = useState("");

    useEffect(() => {
        const fetchImage = async () => {
            const storageRef = ref(storage, "/Hero.jpg"); // Update path accordingly
            try {
                const url = await getDownloadURL(storageRef);
                setBgImageUrl(url);
            } catch (error) {
                console.error("Error fetching image from Firebase:", error);
            }
        };

        fetchImage();
    }, []);

    return (
        <>
            {bgImageUrl && (
                <Image src={bgImageUrl} alt="Hero Image" fill={true} />
            )}
        </>
    );
};

export default Hero;

To troubleshoot this issue, I minimized the components until only one was remaining with the problem. It appears on my homepage and renders the image locally, but the build process fails.

ReferenceError: window is not defined at /home/cjbellmyer/code/green_country/.next/server/app/page.js:512:5749 at 4860 (/home/cjbellmyer/code/green_country/.next/server/app/page.js:512:16127) at t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) at 7586 (/home/cjbellmyer/code/green_country/.next/server/app/page.js:848:47) at t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) at 9165 (/home/cjbellmyer/code/green_country/.next/server/app/page.js:512:2954) at t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) at F (/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94693) at j (/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:93244) at rP (/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33905) Generating static pages (4/4)

Export encountered errors on following paths: /page: /

I have attempted setting a default path in my useState, as well as using a conventional img tag instead of the Image component.

Answer №1

It appears to be a simple solution, but why isn't it working as expected?

The first step is understanding the cause of reference errors.

There are various reasons for these errors, with the most common being attempting to use something before it is defined or when it is not available in the current scope.

Although specifying 'use client' implies that a specific component should run on the client side, it may not automatically address compatibility issues with certain client-side code, such as browser APIs like window and document.

I'm not referring to those at all, so why am I still encountering a reference error?

While I don't directly utilize window, Firebase does, leading to the window reference error.

To resolve this issue, ensure that any code accessing Firebase is only utilized in a client context. One way to achieve this is by verifying if window is available before proceeding:

const fetchImage = async () => {
    // Add this check
    if (typeof window !== 'undefined') {
        const storageRef = ref(storage, "/Hero.jpg"); // Update path accordingly
        try {
            const url = await getDownloadURL(storageRef);
            setBgImageUrl(url);
        } catch (error) {
            console.error("Error fetching image from Firebase:", error);
        }
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to styling a sub-child element within the first child using TailwindCSS?

Currently working with React (Next.js) and TailwindCSS. <ul> <li> <h1 className="bg-red-400">first</h1> </li> <li> <h1 className="bg-green-400">second</h1> </li> &l ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

The elusive Tailwind Switch fails to make an appearance

I tried to replicate the direct switch example from TailwindUI. Here is the original code: /* This example requires Tailwind CSS v2.0+ */ import { useState } from 'react' import { Switch } from '@headlessui/react' function classNames( ...

Struggling to understand how to define and utilize Static variables in TypeScript? If you're finding that they are consistently coming up

export class myClass implements OnInit { counter = 0; static counter: any; onListItemClick(PackDef: PackDefinition): void { this.itemClicked.emit(PackDef); this.counter++; console.log(this.counter); } } and.. import { myClass } from '. ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

Resolve CORS issue by implementing WPGraphQL plugin as the back end and integrating NextJS as the front end

Recently, I encountered a challenging error after transferring a website from Google Cloud. Initially running on Nginx, the site is now hosted on an Apache server. The website comprises two parts: front-end (hosted on Vercel NextJS) and a backend WordPres ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

What is the best way to transform HeadersInit into an Object<string,string> data type?

In short, I am faced with the task of converting the headers of a RequestInit into a format that another library can comprehend. This particular library requires the headers to be in the format of Object<string, string>. Initially, I attempted someth ...

The concept of overloaded function types in TypeScript

Is it possible to create an overloaded function type without specifying a concrete function? By examining the type of an overloaded function, it appears that using multiple call signatures on an interface or object type is the recommended approach: functi ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

The Tilelayer URL is being rendered a total of six times

Currently, I am facing an issue with a map layer that contains a custom image. The problem lies in the fact that this image is being rendered six times even though the Tilelayer component is only rendered once. <MapContainer className ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Is there a way to send functions from a main component to manage events in a sub component with Next.JS?

I have undertaken the task of creating a FormGenerator.jsx component in Next.js to dynamically generate forms based on an array of objects passed to it. The FormGenerator will loop through each object, rendering child components like TextField and TextArea ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...