Hints
Hints for how to resolve common issues.
window is not defined
The following error usually means that client-side code is wrongfully executed on the server-side.
ReferenceError: window is not defined
at someFunction (~/my-app/some/file.js:5:3)
at someCallerFn (~/my-app/some/other-file.js:7:3)
// ~/my-app/some/file.ts
// This file should be loaded only on the client-side
export function someFunction() {
window.alert('hello')
}
// ~/my-app/some/other-file.ts
// This file is loaded on both client- and server-side
import { someFunction } from './file.js'
function someCallerFn() {
someFunction()
}
The error, which is thrown by Node.js(/Bun/Deno), is that the window
object is defined on the client-side only: Node.js doesn't know about window
and therefore throws an error.
The solution is typically one of the following:
- Make sure
someFunction()
is called only on the client-side:// ~/my-app/some/other-file.ts // This file is loaded on both client- and server-side import { someFunction } from './file.js' function someCallerFn() { someFunction() }
// ~/my-app/somewhere/else.ts // This file is loaded on the client-side only. function someThirdFn() { // We can call someFunction() here. someFunction() }
- Or make
someFunction()
isomorphic:// ~/my-app/some/file.ts // This file should be loaded only on the client-side // This file can be loaded on both client- and server-side function someFunction() { window.alert('hello') if (isBrowser()) window.alert('hello') } function isBrowser() { return typeof window !== 'undefined' }
We recommend the first approach whenever possible, because it's best to minimize isomorphic code to a strict minimum, for cleaner code and to avoid client-side bloat (loading server-side code on the client-side increases client bundle sizes and therefore slows down your app).
⚠️Another common technique is to define the
window
object on the server-side, for example withssr-window
, but we recommend against this approach because it may break a library that relies ontypeof window !== 'undefined'
to test whether the code is running on the client or server-side.
You can use
.client.js
to structure and clarify where your files are loaded.