ReferenceError: document is not defined TypeScript
Introduction
When you encounter the ReferenceError: document is not defined in a TypeScript project, it usually means that your code is trying to access the document object from the browser’s DOM while running in an environment that does not provide it—most commonly Node.js or a server‑side build process. This article explains why the error occurs, where it typically appears, and how to resolve it using proper TypeScript configurations, DOM typings, and coding patterns. By the end, you’ll have a clear roadmap to eliminate the error and write TypeScript that works without friction both in the browser and in non‑DOM contexts.
Understanding the Error
What is a ReferenceError?
A ReferenceError is thrown when the JavaScript engine cannot find a variable or object that you are trying to use. In this case, document is a global variable that exists only in web browsers. If you reference document in a context where it is absent, the engine raises:
ReferenceError: document is not defined
Why TypeScript Shows the Error
TypeScript is a superset of JavaScript, but it adds static typing. Consider this: g. Because of that, when you compile a TypeScript file targeting ES5 or ES6 without specifying a DOM lib, the compiler assumes a pure JavaScript environment (e. , Node). As a result, any reference to browser‑only globals like document, window, or navigator will trigger a ReferenceError at runtime and may also generate a compile‑time warning if the appropriate type definitions are missing.
Common Scenarios
| Scenario | Typical Cause | Example |
|---|---|---|
| Running TS in Node | Using import/require with code that manipulates the DOM (e.Now, g. Now, , document. getElementById) |
const el = document.querySelector('div'); |
| Missing DOM typings | tsconfig.On the flip side, json does not include dom or es2020 libs, so document is typed as any or not at all |
No /// <reference types="dom" /> |
| Universal/Isomorphic code | Same file is executed both client‑side and server‑side, causing document to be undefined on the server |
if (typeof document ! == 'undefined') { … } |
| Build step that strips globals | Tools like Webpack or Rollup target Node for server‑side rendering without polyfills | Server bundle tries to read `document. |
Understanding the context in which the error appears is the first step toward fixing it.
Solutions and Best Practices
1. Use the Correct tsconfig.json Settings
Add the DOM library to your TypeScript configuration:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["DOM", "ES2020"],
"moduleResolution": "Node",
"allowJs": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
lib: Including"DOM"supplies the global declarations (document,window, etc.).target: Choose a modern ECMAScript version that supports the APIs you need.
If you are building for both browser and Node, consider using "dom" together with "esnext" and guard DOM usage with typeof window !== "undefined" Most people skip this — try not to..
2. Guard Access to document
Wrap any DOM manipulation in a runtime check:
if (typeof document !== "undefined") {
const element = document.createElement("div");
document.body.appendChild(element);
}
This prevents the ReferenceError when the code runs in Node.
3. apply TypeScript’s DOM Types
When the DOM library is included, TypeScript knows the shape of document and other globals. You can import them explicitly for better IntelliSense:
import { Document } from "typescript/lib/lib-dom";
const doc: Document = document; // No error
Note: The import path may differ based on your TypeScript version; the key point is that the types are now available.
4. Separate Client‑Side and Server‑Side Code
- Client‑only modules: Place DOM‑related code in files that are imported only in the browser (e.g., using dynamic
import()with a check forwindow). - Server‑side modules: Keep pure logic (data fetching, business rules) in files that never reference
document.
5. Use Polyfills or Alternatives
If you truly need DOM functionality on the server (e.g., for server‑side rendering), consider:
- jsdom: A Node.js implementation of the DOM that provides a
documentobject. - DOM‑like libraries: For simple tasks, use packages such as
linkedomwhich expose a lightweight DOM API.
These polyfills let you write the same code while the underlying environment supplies the missing globals And it works..
6. Enable allowSyntheticDefaultImports and esModuleInterop
When using modules that import the DOM (e.g., import { querySelector } from "some-dom-lib"), ensure your config allows synthetic default imports:
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
This reduces the chance of mismatched type definitions that could indirectly cause runtime errors Simple as that..
Using TypeScript with DOM Types – Step‑by‑Step
-
Install the DOM lib (if not already present) Not complicated — just consistent..
npm install --save-dev @types/nodeThe
@types/nodepackage includes thelib.dom.d.tsfile that definesdocument,window, and related globals. -
Add the lib to
tsconfig.json(as shown earlier). -
Write code with proper typings:
// utils.On top of that, const p = document. ts export function createParagraph(text: string): HTMLParagraphElement { // The compiler now knows `document` exists. createElement("p"); p. -
Compile and run in the browser (or a bundler that injects a DOM environment). The error disappears because the type system and runtime both recognize
documentThe details matter here..
Example: Fixing a Real‑World Bug
Problem: A utility library that extracts meta tags fails in a Node environment.
// metaExtractor.ts
export function getMetaTag(name: string): string | undefined {
// ❌ Throws ReferenceError in Node
return document.querySelector(`meta[name="${name}"]`)?.content;
}
Fix:
// metaExtractor.ts
export function getMetaTag(name: string): string | undefined {
if (typeof document === "undefined") {
// Running on the server – return a placeholder or throw a
The missing guard can be completed in a way that makes the function safe for both environments:
```ts
// metaExtractor.ts
export function getMetaTag(name: string): string | undefined {
if (typeof document === "undefined") {
// Running on the server – there is no DOM to query.
// Returning undefined signals “not found” without throwing,
// but you could also throw a dedicated error if that better fits your API.
return undefined;
}
const meta = document.querySelector(`meta[name="${name}"]`);
return meta?.content;
}
7. Load DOM‑specific code only in the browser
When a module truly depends on the DOM (for example, a component library that manipulates elements), wrap its import in a runtime check:
// utils/browserOnly.ts
let browserModule: {
setClass: (el: HTMLElement, cls: string) => void;
};
if (typeof window !Consider this: == "undefined") {
// Dynamic import ensures the bundle is omitted from the server build. Now, import(". /browserOnlyModule").
// Later in your code
if (browserModule) {
browserModule.setClass(element, "active");
}
The if (typeof window !== "undefined") guard guarantees that the import is executed only when the current runtime provides a window object. In a Node environment the promise never resolves, leaving browserModule undefined and preventing any accidental ReferenceError.
8. Adopt a lightweight abstraction layer
If your codebase frequently needs to differentiate between server and client, consider extracting DOM interactions behind a small wrapper:
// domAdapter.ts
export const dom = {
createElement: (tag: string) => {
if (typeof document !== "undefined") {
return document.createElement(tag);
}
// Fallback for non‑DOM environments – you could return a mock object.
throw new Error("DOM not available");
},
querySelector: (selector: string) => {
if (typeof document !== "undefined") {
return document.querySelector(selector);
}
return null;
},
// add other methods as needed
};
All DOM‑dependent utilities then import dom instead of referencing document directly. This centralizes the check, makes the intent clearer, and eases future migration to environments where a true DOM might not exist (e.g., Web Workers with a simulated DOM) That's the whole idea..
9. Use a testing environment that mimics the DOM
When writing unit tests for functions that rely on the DOM, configure your test runner to run in a DOM‑like context (e.g., Jest with jsdom or Vitest with the built‑in node environment). This prevents false positives/negatives caused by the absence of document during test execution and gives you confidence that the same code path works in the browser The details matter here..
10. Concluding thoughts
By installing the appropriate TypeScript lib, enabling the DOM typings in tsconfig.Polyfills such as jsdomorlinkedom provide a viable shim when server‑side rendering truly requires a DOM, while careful module segmentation keeps the bundle lean and the codebase maintainable. json, and employing runtime guards (whether via typeof document === "undefined" checks, dynamic imports, or a dedicated abstraction layer), you eliminate the “document is not defined” error without sacrificing type safety. Following these steps ensures that your TypeScript project can confidently interact with the DOM in the browser and fail gracefully—or not at all—when executed on the server.