When utilizing useEffect in Next.js, an error may occur stating that the window is

It seems like there is a challenge with executing script code server side in next.js 13 when it needs to be executed client side. Currently, I am trying to implement the bulma calendar found at

When importing the required library:

import PasswordStrengthBar from 'react-password-strength-bar';

Even if I use useEffect:

useEffect(() => {
    console.log('HERE WINDOW:', window, bulmaCalendar);
    bulmaCalendar.attach('#calendar', {});
}, []);

I encounter a

ReferenceError: window is not defined
.

file:<...>/node_modules/bulma-calendar/dist/js/bulma-calendar.min.js (1:208)

An interesting observation is that this error occurs on full page refresh in development mode and the line

console.log('HERE WINDOW:', window, bulmaCalendar);
is skipped. However, modifying the source file to trigger fast refresh resolves the issue until another page refresh triggers the error again. If the line
bulmaCalendar.attach('#calendar', {});
is removed, the error does not occur (but neither does the initialization). It appears that some optimization prevents the import from running if bulmaCalendar is not utilized, but once used, server-side initialization code requiring the window object executes.

I attempted to use next/script for client-side imports, but it seems limited to loading scripts via link and does not support bundling scripts from node_modules. Alternatively, the variable bulmaCalendar may become inaccessible after loading in the tag.

This problem is reminiscent of issues encountered with other client-side scripts, such as geolocation retrieval.

How can I prevent this issue and ensure that the script runs exclusively on the client side without manual intervention?

import React, { useEffect } from 'react';

import bulmaCalendar from 'bulma-calendar/dist/js/bulma-calendar.min.js';


const Sample = () => {

  useEffect(() => {
    console.log('HERE WINDOW:', window);
    bulmaCalendar.attach('#calendar', {});
  }, []);

  return (
    <main>
      <form>
        <input
          id="calendar"
          type="date"
        />
      </form>
    </main>
  );
}

https://codesandbox.io/p/sandbox/interesting-marco-264zc3?file=%2Fpages%2Findex.tsx&selection=%5B%7B%22endColumn%22%3A20%2C%22endLineNumber%22%3A11%2C%22startColumn%22%3A20%2C%22startLineNumber%22%3A11%7D%5D

Answer №1

When facing an issue with an import not working during SSR, there are two possible approaches to resolve it:

  1. Stubbing dependencies:

    While not the preferred method due to potential conflicts with other libraries that check for global window objects, one option is to implement a workaround like global.window = {}.

  2. Implementing a client-side import:

    This alternative is recommended:

  useEffect(() => {
    console.log("HERE WINDOW:", window);
    import("bulma-calendar/dist/js/bulma-calendar.min.js").then(
      (bulmaCalendar) => {
        bulmaCalendar.default.attach("#calendar", {});
      }
    );
  }, []);

The approach here is to only import bulmaCalendar when it is actually needed, avoiding premature loading during server-side rendering.

Check out this Codesandbox example with the fix applied (Please note that the CSS may not display correctly in this sandbox).

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

Issues with rotating the camera in three.js are causing functionality problems

I have been working on a code snippet to rotate my camera around the x-axis within a three.js environment: var cameraOrginX = 0, cameraOrginY = 0, cameraOrginZ = 0; var cameraEndX = 0, cameraEndY = 0, cameraEndZ = 1000; var angle = 0; function initialize ...

Enhancing Kendo Grid with Checkbox Columns

I am facing a situation with my kendo grid where I need to insert two checkbox columns in addition to the existing set of columns. <script id="sectionPage" type="text/kendo-tmpl"> @(Html.Kendo().Grid<SectionPageModel>() .Na ...

What is the best way to trigger a function exclusively upon clicking a particular element?

My goal is to enable the user to interact with the model by positioning cubes in space upon clicking the "Cubes Mode" button. I currently have a script from the three.js website that achieves this, but I want it to only run when the mentioned button is cli ...

Determining the largest range possible in a sorted array of integers

I need help with a JavaScript implementation for the following challenge. Imagine we have a sorted array: [1,2,5,9,10,12,20,21,22,23,24,26,27] I want to find the length of the longest consecutive range that increments by 1 without duplicates. In the ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

What methods are available for implementing hover effects within attributes using a JavaScript object?

const customPanelStyle = { 'background-color': 'red', 'border': '1px solid green', ':hover'{ 'background': 'blue' } } class some extends React.Component{ rende ...

Ways to organize backbone models, views, and collections using vim?

I am a fan of vim's folding feature, but I have encountered some challenges when trying to fold backbone models, views, and collections. This is because backbone does not follow the traditional prototype syntax, but instead uses a .extend() based synt ...

Is it possible to retrieve the chosen options text from a select menu using jQuery with the feature of "Dynamic option values"?

I need assistance with displaying dynamic drop-down values where only the id values are presently available. What would be the best approach to achieve this? <div class="form-group"> <select class="wp-form-control" id="joblocation" name="jobl ...

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

Is there a way to incorporate two different layouts within a single Next.js project?

After creating a blog project, I realized the need for an admin panel. However, I prefer not to use the global layout within my admin area. Is there a way to incorporate two different layouts in the same project? https://i.sstatic.net/WiTai.png I attempt ...

Attain the ability to distinguish errors in Promises

Context In my project, I have implemented a REST API that interacts with MongoDB using Node.js and Express. The issue at hand involves handling errors based on different scenarios when making requests to the NoSQL database. Challenge The current impleme ...

Dealing with the process of single sign out from Identity Server4 using frontchannel

We have a unique solution that utilizes multiple Single Page Applications (SPAs) developed in both Angular and AngularJS. These applications integrate the oidc-client-js library for authentication with Identity Server 4. However, due to limitations of Angu ...

Encountering a 404 error while attempting to establish a connection between Express and React

My attempt to make a simple API request for bitcoin values is encountering some issues. When I enter in my Chrome browser, I receive a "Cannot Get /" message with a 404 error in the dev tools stating "GET 404 (Not Found)". However, when I visit , I succ ...

ReactJS & MobX: Unusual TypeError Occurs - Functionality Issue?

This code snippet defines the SidenavStore.js, which determines if the Sidenav should be visible or not by default: const SidenavStore = types .model('SidenavStore', { isSidenavVisible: types.optional(types.boolean, true), }) .actions( ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...

Module not defined error

Here is the code for my HTML page: <!DOCTYPE html> <!-- define angular app --> <html ng-app="daily"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" c ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

Oops! Looks like an issue has popped up: using require() of an ES module is not supported when using recharts in combination with next.js

I've noticed some similar questions, but none of them seem to address my particular issue. I'm currently working on a webapp using next.js (with typescript). Within the app, I am utilizing recharts, however, I am encountering a compilation error: ...