After upgrading @googlemaps/js-api-loader from 2.0.2 to 2.1.0, our Next.js application fails during next build --webpack with:
ReferenceError: window is not defined
> Build error occurred
Error: Failed to collect page data for /page-using-google-maps
Environment
@googlemaps/js-api-loader: 2.1.0
- Next.js (Pages Router)
next build --webpack
Usage
We're importing into an effect as follows:
import { importLibrary, setOptions } from "@googlemaps/js-api-loader";
useEffect(() => {
setOptions({ key: apiKey, v: "weekly" });
Promise.all([
importLibrary("maps"),
importLibrary("marker"),
importLibrary("streetView"),
]);
}, []);
The calls to setOptions() and importLibrary() are inside a useEffect, so they should only execute client-side.
Investigation
We've traced through our component tree:
- The page itself is exported with
ssr: false using next/dynamic
- Map components only access
window and google.maps inside useEffect callbacks
- There are no obvious top-level
window references in our application code
- The issue only occurs after upgrading from 2.0.2 to 2.1.0
- We can use 2.1.0 only if we import
@googlemaps/js-api-loader inside the useEffect block
Questions
- Were there any changes between 2.0.2 and 2.1.0 that introduced browser-specific initialisation at import time?
- Is
@googlemaps/js-api-loader expected to be safe to import in SSR environments such as Next.js, provided that setOptions() and importLibrary() are only called client-side?
After upgrading
@googlemaps/js-api-loaderfrom 2.0.2 to 2.1.0, our Next.js application fails duringnext build --webpackwith:Environment
@googlemaps/js-api-loader: 2.1.0next build --webpackUsage
We're importing into an effect as follows:
The calls to
setOptions()andimportLibrary()are inside auseEffect, so they should only execute client-side.Investigation
We've traced through our component tree:
ssr: falseusingnext/dynamicwindowandgoogle.mapsinsideuseEffectcallbackswindowreferences in our application code@googlemaps/js-api-loaderinside theuseEffectblockQuestions
@googlemaps/js-api-loaderexpected to be safe to import in SSR environments such as Next.js, provided thatsetOptions()andimportLibrary()are only called client-side?