Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js ERR_INVALID_ARG_TYPE: the argument must be of type

ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.

~4 min readNode.js
#nodejs#errors#fs#streams
Bold white headline reading INVALID ARG TYPE with a Node crate rejecting an amber undefined block at a cyan type gate.

Introduction & Quick Summary

A script that has been running nightly dies on one input:

code
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined at Object.openSync (node:fs:596:3) at Object.readFileSync (node:fs:518:28)

Quick answer: ERR_INVALID_ARG_TYPE is Node's argument validator refusing a value whose type is wrong, and Received undefined names the value. Find which argument the message quotes, then decide whether the caller should pass a string or the callee should handle absence.

js
const file = process.env.CONFIG_PATH; if (typeof file !== "string") { throw new Error("CONFIG_PATH is required"); // fail with a message that names the setting } const raw = fs.readFileSync(file, "utf8");

The error is always a TypeError with code === "ERR_INVALID_ARG_TYPE". Node validates arguments at the boundary of every built-in module, so the same code appears with dozens of messages; what changes is the quoted argument and the expected type:

  • The "path" argument must be of type string — an env var, a config field or a database column came back undefined.
  • The "chunk" argument must be of type string or an instance of Buffer — a stream was written with an object or undefined.
  • The "data" argument must be of type string or an instance of Buffer — writeFile received a non-serializable value.
  • The "encoding" argument must be of type string — an options object was passed in the wrong position.

Every one of these is a caller-side mistake, not a Node bug. The value arrived from somewhere untyped: process.env, JSON.parse, a request body, a database row, or an array index that returned undefined.

Core Mechanics, Signatures & Reproducible Setup

Reproduce without installing anything:

bash
node -e "require('fs').readFileSync(process.env.MISSING_FILE)" node -e "require('fs').writeFileSync('/tmp/x', undefined)" node -e "require('crypto').createHash('sha256').update(undefined)"

Each prints the same error class with a different argument quoted. The validator lives in Node's internal validateString, validateBuffer and validateFunction helpers; it checks the value before any I/O happens, which is why the stack shows the public function (readFileSync) and not the caller.

Message fragmentArgumentAccepted typesUsual source of the bad value
"path" ... string or an instance of Buffer or URLfirst fs argumentstring, Buffer, URLprocess.env.X, config key, req.query.file
"data" ... string or an instance of BufferwriteFile payloadstring, Buffer, TypedArrayJSON.stringify(undefined) returns undefined
"chunk" ... string or an instance of Bufferstream.write payloadstring, Buffer, Uint8Arrayan object written to a byte stream
"encoding" ... stringsecond or third argumentBufferEncodingoptions object in the wrong slot
"callback" ... functionlast argumentfunctionpromisified call without a callback
"signal" ... instance of AbortSignalabort optionAbortSignalan EventEmitter or a custom signal
"fd" ... numberfile descriptorintegera string path passed to fs.read

Key Comparison Table

FixExampleWhen it is rightTrade-off
Validate at the boundaryif (!path) throw new Error(...)values from env, HTTP, DBone check per entry point
Default the valueconst dir = process.env.DIR ?? "./data"optional settingshides a misconfiguration
Fix the type in placeString(id) around a numeric idid is a number by design"undefined" string if the value is missing
Schema validationz.string().parse(input)request payloadsadds a dependency
TypeScript narrowingtypeof v === "string"typed codebasestypes do not reach runtime data
Let the callee failcatch err.codelibrary codeerrors surface late

What the same failure looks like across Node versions:

Node versionMessage tailNotes
14 and 16Received type undefinedno value printed
18Received undefinedactual value shown for primitives
20Received undefinedcause set when wrapping
22Received undefinedsame validator, stricter AbortSignal checks

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. process.env values are string or undefined

js
import { readFileSync } from "node:fs"; import path from "node:path"; const configPath = path.join(process.env.APP_HOME, "config.json"); // throws if APP_HOME is unset

path.join accepts strings only, so a missing variable becomes the quoted argument. Resolve it once at startup with an explicit fallback or an error that says what is missing:

js
const home = process.env.APP_HOME; if (!home) throw new Error("APP_HOME is not set; see .env.example"); const configPath = path.join(home, "config.json");

The same trap appears with numeric ids: fs.readFile(req.params.id) fails when the router yields a number. String(id) fixes the type, but check for undefined first, or the file will be named "undefined".

2. Streams: write(undefined) and object-mode confusion

js
const { Transform } = require("node:stream"); const upper = new Transform({ transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); }, }); upper.write(undefined); // ERR_INVALID_ARG_TYPE on "chunk" upper.write({ text: "hi" }); // same, a byte stream cannot carry objects

A transform that needs objects must declare objectMode: true on both ends. When a stream receives values from a parser, assert the result before writing:

js
function writeLine(stream, line) { if (typeof line !== "string") { throw new TypeError(`expected string, got ${typeof line}`); } stream.write(line.endsWith("\n") ? line : line + "\n"); }

The related failure, write after end, comes from writing to a stream that was already ended, which is a lifecycle bug rather than a type bug.

3. Buffers, encodings and argument positions

js
Buffer.from(undefined); // "value" must be of type string, Buffer, ArrayBuffer... Buffer.from("deadbeef", "hex"); // ok crypto.createHash("sha256").update(payload); // "data" must be string, Buffer, TypedArray, DataView

JSON.stringify(undefined) returns undefined, not "undefined":

js
const body = JSON.stringify(row); // undefined when row holds only functions or is undefined fs.writeFileSync(out, body); // ERR_INVALID_ARG_TYPE on "data"

Guard the serialization step, and check what you actually have with the JSON formatter before writing. Base64 and hex payloads are a common source of encoding mixups; the Base64 encoder shows whether a string is already encoded.

4. HTTP handlers and Content-Type shortcuts

js
app.post("/upload", (req, res) => { const { filename } = req.body; // undefined when the body parser is missing fs.writeFileSync(path.join(uploadDir, filename), req.file?.buffer); });

Here the first bad argument is filename, and if it existed the second would be the buffer. Both values come from the request, so validate the whole shape once:

js
function requireUpload(body) { if (typeof body?.filename !== "string" || !body.filename) { throw Object.assign(new Error("filename is required"), { status: 400 }); } return body.filename; }

The same applies to res.write(chunk) in a handler that forgot to return early: a void return value reaches write. Passing null where an options object is expected produces The "options" argument must be of type object. Received null, which reads like a different bug until you look at the call site.

5. Validation layers that keep the error out of production

Three levels, cheapest first:

js
// 1. local guard function assertString(value, name) { if (typeof value !== "string") { throw new TypeError(`${name} must be a string, received ${typeof value}`); } return value; } // 2. schema at the boundary import { z } from "zod"; const Job = z.object({ input: z.string(), outDir: z.string().min(1) }); const job = Job.parse(message); // 3. typed accessor for env const env = { get outDir() { return assertString(process.env.OUT_DIR, "OUT_DIR"); }, };

With TypeScript, noUncheckedIndexedAccess turns rows[0] into Row | undefined, which surfaces the missing value at compile time. An env file is easier to inspect with the env file formatter than by logging values one at a time.

The stack starts inside node:fs, so the useful frame is the second or third one. node --enable-source-maps --stack-trace-limit=50 app.js makes it legible, and wrapping the call in a helper that names the operation (readJsonConfig, writeSnapshot) turns a generic internal frame into a line that says which file the program was trying to touch.

Common Compilation/Runtime Mistakes & Version Gotchas

Assuming String(value) is validation. It converts undefined to "undefined", which passes every type check and creates a file with that name.

Passing an options object where a string belongs. fs.readFileSync(path, { encoding: "utf8" }) is correct, but fs.readFileSync(path, "utf8", { flag: "r" }) and similar reordered calls produce The "encoding" argument must be of type string. Check the signature for the Node version you deploy.

Relying on instanceof Buffer across realms. A Buffer from a vm context fails the check even though it is valid; use Buffer.isBuffer(value).

Ignoring AbortSignal validation. Node 18+ checks the signal strictly; an emitter-like object with addEventListener fails with The "signal" argument must be an instance of AbortSignal.

Version notes. Node 18 changed the message to include the received value, so log-based alerting that matches the old text stops firing. Node 20 exposes err.cause on wrapped errors. In Node 22, fs callbacks and Buffer validation are unchanged, but the newer styleText and WebSocket APIs use TypeError for their own argument checks, which means a TypeError alone no longer implies a Node builtin.

Reference: Node.js errors and fs.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

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

All Node.js guides

More in Node.js

All Node.js guides

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