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.

Introduction & Quick Summary
A script that has been running nightly dies on one input:
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.
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 backundefined.The "chunk" argument must be of type string or an instance of Buffer— a stream was written with an object orundefined.The "data" argument must be of type string or an instance of Buffer—writeFilereceived 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:
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 fragment | Argument | Accepted types | Usual source of the bad value |
|---|---|---|---|
"path" ... string or an instance of Buffer or URL | first fs argument | string, Buffer, URL | process.env.X, config key, req.query.file |
"data" ... string or an instance of Buffer | writeFile payload | string, Buffer, TypedArray | JSON.stringify(undefined) returns undefined |
"chunk" ... string or an instance of Buffer | stream.write payload | string, Buffer, Uint8Array | an object written to a byte stream |
"encoding" ... string | second or third argument | BufferEncoding | options object in the wrong slot |
"callback" ... function | last argument | function | promisified call without a callback |
"signal" ... instance of AbortSignal | abort option | AbortSignal | an EventEmitter or a custom signal |
"fd" ... number | file descriptor | integer | a string path passed to fs.read |
Key Comparison Table
| Fix | Example | When it is right | Trade-off |
|---|---|---|---|
| Validate at the boundary | if (!path) throw new Error(...) | values from env, HTTP, DB | one check per entry point |
| Default the value | const dir = process.env.DIR ?? "./data" | optional settings | hides a misconfiguration |
| Fix the type in place | String(id) around a numeric id | id is a number by design | "undefined" string if the value is missing |
| Schema validation | z.string().parse(input) | request payloads | adds a dependency |
| TypeScript narrowing | typeof v === "string" | typed codebases | types do not reach runtime data |
| Let the callee fail | catch err.code | library code | errors surface late |
What the same failure looks like across Node versions:
| Node version | Message tail | Notes |
|---|---|---|
| 14 and 16 | Received type undefined | no value printed |
| 18 | Received undefined | actual value shown for primitives |
| 20 | Received undefined | cause set when wrapping |
| 22 | Received undefined | same validator, stricter AbortSignal checks |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. process.env values are string or undefined
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 unsetpath.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:
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
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 objectsA transform that needs objects must declare objectMode: true on both ends. When a stream receives values from a parser, assert the result before writing:
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
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, DataViewJSON.stringify(undefined) returns undefined, not "undefined":
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
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:
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:
// 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 documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js: ERR_DLOPEN_FAILED invalid ELF header
Invalid ELF header means a native addon was built for another OS or architecture. Rebuild it inside the target image instead of copying node_modules.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js 26 upgrade: rmdir, native addons and removed flags
Three breaks stop a deploy: rmdir with recursive throws, the transform-types flag is gone, and the module ABI moved to 147.
Node.js JWT invalid signature: JWKS Rotation and Clock Skew
One message covers three bugs: the wrong key type for RS256 or ES256, a JWKS cache that never refreshes after a kid rotation, and a clock that drifted.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.