How to Fix “document is not defined” in Node.js
ReferenceError: document is not defined appears when code running on Node.js uses document, which exists only in browsers. Node.js has neither document nor window. For tests, set the Vitest environment to jsdom or happy-dom. For code you run directly with node, split the code with typeof document, and the error goes away.
It appears when I ran screen-handling code written for the browser with the node command, and when I wrote a test in Vitest for a function that changes the DOM. In my test environment, both cases produced the error. I confirmed the full message and that the error disappears after the fixes below.
The test environment was Ubuntu 24.04, Node.js 22.23.4 (npm 10.9.9), Vitest 5.1.0, jsdom 31.0.0, and happy-dom 21.0.4. I did not test the same error in Jest, in server-side rendering (SSR) with frameworks such as Next.js, or on Windows and macOS.
Full error message when running with node
I prepared a browser function that puts a greeting into the #app element. src/greet.js is as follows.
export function renderGreeting(name) {
const el = document.querySelector('#app');
el.textContent = `こんにちは、${name}さん`;
return el.textContent;
}
main.js, which calls it, is as follows.
import { renderGreeting } from './src/greet.js';
renderGreeting('ねこ');
When I ran node main.js in the test environment (Ubuntu 24.04, Node.js 22.23.4), it stopped with the output below (exit code 1). The paths are example values.
$ node main.js
file:///path/to/app/src/greet.js:2
const el = document.querySelector('#app');
^
ReferenceError: document is not defined
at renderGreeting (file:///path/to/app/src/greet.js:2:14)
at file:///path/to/app/main.js:3:1
at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
Node.js v22.23.4
ReferenceError: document is not defined means that a variable named document is not defined. The greet.js:2 line at the top and the ^ mark show where execution stopped. The at renderGreeting (...) line below shows that the error happened inside renderGreeting, which was called on line 3 of main.js.
The list of global objects in Node.js includes neither document nor window. When I checked with typeof in the test environment, I got the following.
$ node -e 'console.log(typeof document, typeof window, typeof navigator)'
undefined undefined object
Only navigator is object. Starting with Node.js 21.0.0, a subset of the browser's navigator is provided as a global navigator. Having navigator does not mean the browser APIs are all there. Code that uses window also stops in the same way, with ReferenceError: window is not defined.
When the error happens just by loading the file, without calling a function
If document is used at the top level of a file (outside any function), the error happens as soon as the file is imported. src/top.js is as follows.
const root = document.getElementById('app');
export function show(text) {
root.textContent = text;
}
I ran main-top.js, which only imports this file without calling show and then runs console.log('読み込み完了'). The message from console.log was not displayed, and the program stopped. The paths are example values.
$ node main-top.js
file:///path/to/app/src/top.js:1
const root = document.getElementById('app');
^
ReferenceError: document is not defined
at file:///path/to/app/src/top.js:1:14
at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
Node.js v22.23.4
A sign of this case is that the stack has no function name and only shows top.js:1:14. I created src/top-fixed.js, which moves the line that uses document into show. Then I created main-top-fixed.js, which imports ./src/top-fixed.js instead, and ran it in the same way, only importing without calling. No error occurred, and the message from console.log was displayed.
export function show(text) {
const root = document.getElementById('app');
root.textContent = text;
}
$ node main-top-fixed.js
読み込み完了
show still uses document, so this fix only addresses the stop at load time. If you also want to call show in node, use the pattern in the section "Split code with typeof when you also want to run it in node" below.
When it happens in Vitest tests
By default, Vitest runs tests in the Node.js environment. The description of the environment option in Vitest's configuration also states that the default is 'node'. So if you write a DOM test as is, you get the same error.
I prepared src/greet.ts, written in TypeScript, and its test src/greet.test.ts.
export function renderGreeting(name: string): string {
const el = document.querySelector<HTMLElement>('#app');
if (!el) throw new Error('#app がありません');
el.textContent = `こんにちは、${name}さん`;
return el.textContent;
}
import { beforeEach, expect, test } from 'vitest';
import { renderGreeting } from './greet';
beforeEach(() => {
document.body.innerHTML = '<div id="app"></div>';
});
test('名前を入れたあいさつを #app に表示する', () => {
expect(renderGreeting('ねこ')).toBe('こんにちは、ねこさん');
expect(document.querySelector('#app')?.textContent).toBe('こんにちは、ねこさん');
});
When I ran it without a configuration file (vitest.config.ts), the test failed (exit code 1). The paths are example values.
$ npx vitest run src/greet.test.ts
RUN v5.1.0 /path/to/app
❯ src/greet.test.ts (1 test | 1 failed) 5ms
× 名前を入れたあいさつを #app に表示する 4ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
FAIL src/greet.test.ts > 名前を入れたあいさつを #app に表示する
ReferenceError: document is not defined
❯ src/greet.test.ts:5:3
3|
4| beforeEach(() => {
5| document.body.innerHTML = '<div id="app"></div>';
| ^
6| });
7|
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
Test Files 1 failed (1)
Tests 1 failed (1)
Start at 19:01:57
Duration 218ms (transform 58%, import 23%, tests 10%, worker 9%)
The stop point was line 5 of the test file, document.body inside beforeEach.
Set the environment to jsdom in the configuration file
If most of the project's tests use the DOM, set the environment to jsdom in vitest.config.ts. This applies to all test files.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
},
});
In my test environment, installing only Vitest did not include jsdom. In Vitest's package.json, jsdom is listed under peerDependencies as an optional peer dependency. When I ran the tests without installing jsdom, the output was MISSING DEPENDENCY Cannot find dependency 'jsdom' and Error: Cannot find package 'jsdom' imported from ... instead of document is not defined, and no tests ran (Test Files no tests).
After installing jsdom with npm install -D jsdom (jsdom 31.0.0 in my test), the tests passed.
$ npx vitest run --reporter=verbose src/greet.test.ts
RUN v5.1.0 /path/to/app
✓ src/greet.test.ts > 名前を入れたあいさつを #app に表示する 13ms
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 19:02:01
Duration 790ms (environment 89%, transform 5%, tests 2%, import 2%, worker 1%)
Use jsdom for only some test files
If only some tests use the DOM, add the comment // @vitest-environment jsdom at the top of that file. This is the Vitest guide's method for setting the environment per file. I deleted the configuration file, added only this comment as line 1 of greet.test.ts, and ran the tests. They passed in the same way.
// @vitest-environment jsdom
import { beforeEach, expect, test } from 'vitest';
import { renderGreeting } from './greet';
You can also use happy-dom instead of jsdom. I installed it with npm install -D happy-dom (21.0.4 in my test) and changed the comment to // @vitest-environment happy-dom. The test passed. The Vitest guide says happy-dom is faster than jsdom but lacks some APIs.
Split code with typeof when you also want to run it in node
If you want the same code to run in both the browser and Node.js, check whether document exists first. If you write if (document), it stopped at that line in my test environment with ReferenceError: document is not defined. In an environment without document, just reading the name causes the error.
typeof does not stop. As the MDN description of typeof explains, applying typeof to an undeclared name does not throw an error and returns "undefined". src/safe.js is as follows.
export function renderGreeting(name) {
const text = `こんにちは、${name}さん`;
if (typeof document === 'undefined') {
return text;
}
document.querySelector('#app').textContent = text;
return text;
}
I ran main-safe.js, which calls this function and logs its return value with console.log. No error occurred, and the greeting text was displayed.
$ node main-safe.js
こんにちは、ねこさん




