Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript: Cannot find name 'process' with @types/node

TS2304 on process or Buffer means the compiler has no Node declarations. Install @types/node, stop excluding it, and align its version to the runtime.

~5 min readTypeScript
#typescript#ts2304#types-node#tsconfig
Bold white headline reading TS2304 NODE with a TypeScript crate missing its node declarations card on the right.

Introduction & Quick Summary

tsc stops on Node globals that obviously exist at runtime:

code
src/server.ts:14:18 - error TS2304: Cannot find name 'process'. src/server.ts:15:22 - error TS2304: Cannot find name 'Buffer'. src/config.ts:7:34 - error TS2503: Cannot find namespace 'NodeJS'. src/db.ts:3:9 - error TS2580: Cannot find name 'require'. Do you need to install type definitions for node?

The code is fine. The compiler just has no declaration for those names: TypeScript ships the DOM and ES libraries, but every Node global — process, Buffer, __dirname, require, module, and the NodeJS namespace — is declared in @types/node, an npm package that is installed separately.

It shows up in fresh projects where only typescript was installed, in monorepos where @types/node sits in another workspace, in a types array that lists test globals and drops node, and in configs shared by browser and server code.

Quick answer: install @types/node at the version matching your runtime major, confirm nothing in types, typeRoots, or lib excludes it, then re-run tsc --noEmit and pin the same types version in CI.

Core Mechanics, Signatures & Reproducible Setup

TypeScript resolves every identifier from three sources: library files selected by lib (lib.es2022.d.ts, lib.dom.d.ts), automatic type packages selected by types, and files you include in the program. Node globals are ambient declarations in @types/node, guarded by /// <reference lib="es2020" />. Without that package the name is undefined, so the compiler reports TS2304 instead of a type error.

Reproduce it in an empty folder:

bash
mkdir ts2304 && cd ts2304 && npm init -y && npm i -D typescript@5.7 npx tsc --init --strict --target es2022 --module nodenext --moduleResolution nodenext mkdir src && echo 'console.log(process.env.NODE_ENV, Buffer.from("hi"))' > src/index.ts npx tsc --noEmit

tsc prints two TS2304 errors. Now add the types package and re-run:

bash
npm i -D @types/node@22 npx tsc --noEmit && echo "clean"

The error disappears because @types/node is picked up from node_modules/@types automatically when types is not set. Two rules follow: the package must be visible from the directory holding tsconfig.json, and once types is present, automatic inclusion stops and only the listed packages load.

Which declaration provides which global:

IdentifierDeclared inNotes
process, Buffer, global@types/nodeabsent from DOM lib
__dirname, __filename@types/nodeCommonJS only at runtime
require, module, exports@types/nodenot defined in ESM output
NodeJS.ProcessEnv, NodeJS.Timeout@types/node namespaceneeds an import in some setups
setTimeout, console, URLboth lib.dom and @types/nodeoverloads differ between them
fetch, Request, Responselib.dom or @types/node 18+Node version decides which is real
describe, it, expect@types/jest or vitest/globalsnever part of Node types

A minimal configuration that behaves the same in CI and in the editor:

{ "compilerOptions": { "target": "ES2022", "lib": ["ES2022"], "module": "nodenext", "moduleResolution": "nodenext", "types": ["node"], "strict": true, "skipLibCheck": true, "noEmit": true }, "include": ["src"] }

lib: ["ES2022"] without DOM is deliberate for a server package: it turns "this code accidentally uses document" into a compile error. fetch, URL, AbortController, console, and timers still resolve, because @types/node declares them once the runtime major is 18 or newer.

Key Comparison Table

Choosing the right switch when node types are missing:

SituationWrong moveCorrect moveWhy
Fresh Next.js or Vite appAdding "types": ["node"] on top of an existing listAppend to the list: ["node", "vite/client"]types replaces, it does not merge
Monorepo packageInstalling @types/node only at the root and relying on hoistingDeclare it in the package's own devDependenciespnpm and Yarn PnP do not hoist by default
Library published to npm"dependencies": { "@types/node": "22" }devDependencies plus "engines"consumers resolve types from their own tree
Test globalstypes: ["jest"]types: ["node", "jest"]listing one package excludes the rest
Mixed browser/serverOne config with lib: ["DOM"]Two configs, tsconfig.app.json and tsconfig.node.jsonDOM globals hide real server errors

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. A types array that silently removed Node

This config looks deliberate and breaks every server file:

{ "compilerOptions": { "types": ["jest"] } }

The fix is additive, and the order does not matter:

{ "compilerOptions": { "types": ["node", "jest"] } }

If tests live in their own project, let tsconfig.test.json extend the production config and add "types": ["node", "jest"] there. Running npx tsc --showConfig prints the effective value after every extends merge, the fastest way to see who removed node.

2. Monorepo and pnpm: types installed, still invisible

With strict node linking, @types/node at the workspace root is not resolvable from packages/api. Install it where the tsconfig lives (pnpm --filter @acme/api add -D @types/node@22), then confirm from the package root:

bash
cd packages/api && node -e "console.log(require.resolve('@types/node/package.json'))"

If that command fails, tsc cannot see the declarations either. A shared base config should not contain typeRoots with a relative path such as "../node_modules/@types", because it resolves from the extending file's directory and breaks one level down.

3. __dirname and require in ES modules

Adding @types/node makes the compile pass, and the program still crashes:

ReferenceError: __dirname is not defined in ES module scope

The types describe both module systems, so the compiler cannot tell which one you emit. Rebuild the path from import.meta.url:

ts
import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; const here = dirname(fileURLToPath(import.meta.url)); export const templatePath = join(here, "templates", "welcome.html");

4. Global fetch disappears when DOM is removed

A server config that drops DOM is a good idea until someone calls fetch and gets error TS2304: Cannot find name 'fetch'. Two fixes, and they are not equivalent: importing fetch from undici works on any Node 18+ runtime regardless of lib, while the bare global needs @types/node 18 or newer and a runtime that exposes it.

ts
import { fetch } from "undici"; // explicit, independent of lib settings const res = await fetch("https://api.example.com/health", { signal: AbortSignal.timeout(1500) });

In a library that still runs on older Node, import undici directly and skip the global.

5. Typing process.env without lying to the compiler

ProcessEnv has an index signature of string | undefined, so const port: number = process.env.PORT fails with TS2322 under strict. Validate once at startup:

ts
function required(name: string): string { const value = process.env[name]; if (!value) throw new Error(`Missing environment variable ${name}`); return value; } export const config = { port: Number(required("PORT")), databaseUrl: required("DATABASE_URL"), } as const;

Custom globals follow the same rule. Put the declaration in a .d.ts inside include, and export nothing:

ts
declare global { // eslint-disable-next-line no-var var __APP_VERSION__: string; } export {};

A .d.ts with a top-level import becomes a module, and declare global inside it stops applying to the project — the usual reason a hand-written global "does not work".

6. A third table for triage

MessageReal causeFirst check
TS2304 Cannot find name 'process'@types/node absent or excludednpm ls @types/node
TS2503 Cannot find namespace 'NodeJS'same, or a .d.ts with no includenpx tsc --showConfig
TS2580 Cannot find name 'require'ESM file emitting requirepackage.json type field
TS2717 Subsequent property declarationstwo copies of @types/nodenpm ls @types/node

Common Compilation/Runtime Mistakes & Version Gotchas

Installing @types/node but pinning an old major. Types are the contract, not a suggestion. npm ls @types/node shows the version actually hoisted; pin the oldest runtime you support and let CI use the same one.

Two copies of @types/node in one program. A dependency that ships its own copy produces duplicate global declarations and the compiler reports TS2717: Subsequent property declarations must have the same type or an incompatible ProcessEnv. An overrides entry in package.json or pnpm.overrides collapses them to one version; skipLibCheck only hides the conflict.

Reaching for declare const process: any or // @ts-ignore. Both remove type safety for every call and outlive the missing dependency by years. A missing package is a project problem, not a line problem.

TypeScript 5.x defaults that changed the result. verbatimModuleSyntax: true rejects import x = require("x") in files the compiler treats as ESM, and moduleResolution: "bundler" resolves node: imports differently from nodenext. After upgrading, run npx tsc --noEmit --extendedDiagnostics and compare the file list with the previous run; a declaration file that dropped out of the program explains most "it compiled yesterday" reports.

Checking environment variables by hand. Dump the real runtime environment with the env formatter to confirm names and casing, and compare two tsconfig files with Diff before blaming the editor. Configs a build step rewrites can be validated with the JSON validator, which catches the trailing commas and BOM characters that make tsc exit before it reports any type error.

Reference material: TypeScript tsconfig reference, types and typeRoots and Node.js globals.

Official references

primary documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.