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>
);
}