Errors in npm

Why is Zipy npm giving a build warning - ‘ReferenceError: window is not defined’ and how to resolve?

Zipy npm module is used in the client’s browser and it uses browser features to capture the Frontend errors and the DOM. While working with NextJS, one of the most common issues that users observe is ‘ReferenceError: window is not defined’.

The above error occurs as NextJS renders code using Server-Side Rendering(SSR) to compile the code that runs on the browser. This can cause the warnings to appear in the build logs. We recommend the following ways to ensure these errors don’t appear. This will ensure Zipy code is instantiated only when the environment in which the code runs is the browser.

1. Approach A - Use typeof

import zipy from "zipyai";
if (typeof window !== "undefined") {
  zipy.init("APIKEY");
}

2. Approach B - Use useEffect

In ReactJS, the useEffect component is triggered only when the component is rendered on the screen. This will ensure Zipy is instantiated only after the component loads on the screen.

import React from "react";
import zipy from "zipyai";

React.useEffect(() => {
    zipy.init("APIKEY");
});

Last updated