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:

  1. 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()
    }
  2. 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 with ssr-window, but we recommend against this approach because it may break a library that relies on typeof 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.

See also