Stack traces

suggest change

A stack trace (or call stack) is a textual report produced by the V8 JavaScript engine detailing the active call frames when an Error is instantiated. In Node.js, understanding how stack traces work—and how to customize, limit, and map them—is essential for debugging asynchronous code and diagnosing production crashes.


1. Anatomy of a Node.js Stack Trace

When an error is instantiated, V8 captures a snapshot of the current execution stack:

function alpha() {
  beta();
}

function beta() {
  throw new Error("Something went wrong");
}

try {
  alpha();
} catch (err) {
  console.log(err.stack);
}

Output:

Error: Something went wrong
    at beta (/app/server.js:6:9)
    at alpha (/app/server.js:2:3)
    at Object.<anonymous> (/app/server.js:10:3)
    at Module._compile (node:internal/modules/cjs/loader:1929:14)
    ... (more Node.js internal frames)

The trace contains:

  1. Header: ErrorName: ErrorMessage (from err.name and err.message).
  2. Frames: Ordered list of execution frames from innermost (beta) to outermost (module entry point). Each frame specifies the function name, file path, line number, and column.

2. Configuring Stack Trace Depth (stackTraceLimit)

By default, V8 captures up to 10 frames. In deep asynchronous pipelines or large frameworks (like NestJS or Express), 10 frames may omit the actual origin of the error.

Expanding the Limit

// Expand stack depth to 50 frames
Error.stackTraceLimit = 50;

// Or capture the complete unbounded stack
Error.stackTraceLimit = Infinity;

You can also set this globally at process startup using Node CLI options:

node --stack-trace-limit=50 app.js

Disabling Traces for High-Throughput Scenarios

If you instantiate many operational error objects where call stacks are never logged, setting Error.stackTraceLimit = 0 eliminates the V8 stack-walking overhead:

Error.stackTraceLimit = 0; // Avoids stack capture overhead
const err = new Error("Fast validation failure");
console.log(err.stack); // Only prints the header, no frames

3. Customizing Traces with V8 APIs

Hiding Utility Frames with Error.captureStackTrace

When authoring custom error classes or assertion utilities, you usually want to exclude the utility's own constructor from the trace:

class DatabaseError extends Error {
  constructor(message) {
    super(message);
    this.name = 'DatabaseError';

    // The second argument omits the constructor frame from err.stack
    Error.captureStackTrace(this, DatabaseError);
  }
}

function queryDatabase() {
  throw new DatabaseError("Connection timeout");
}

try {
  queryDatabase();
} catch (err) {
  console.log(err.stack);
  // The first 'at' line will point directly to queryDatabase(), NOT DatabaseError constructor
}

Parsing Structured Stack Frames with Error.prepareStackTrace

V8 allows intercepting and formatting stack traces programmatically via Error.prepareStackTrace:

function getCallerInfo() {
  const originalPrepare = Error.prepareStackTrace;
  try {
    Error.prepareStackTrace = (err, callSites) => callSites;
    const err = new Error();
    const callSites = err.stack; // Now an array of CallSite objects

    // Index 0: getCallerInfo
    // Index 1: the immediate caller of getCallerInfo
    const caller = callSites[1];
    return {
      fileName: caller.getFileName(),
      functionName: caller.getFunctionName() || 'anonymous',
      lineNumber: caller.getLineNumber(),
      columnNumber: caller.getColumnNumber()
    };
  } finally {
    Error.prepareStackTrace = originalPrepare;
  }
}

function processPayment() {
  console.log('Invoked by:', getCallerInfo());
}

processPayment();

Common CallSite methods include:


4. Asynchronous Stack Traces

Prior to Node.js 12, asynchronous callbacks and timers lost their execution context, resulting in truncated traces showing only the internal event loop tick.

Modern V8 implements Zero-Cost Async Stack Traces for async/await:

async function stepThree() {
  await new Promise((resolve) => setTimeout(resolve, 50));
  throw new Error("Asynchronous failure!");
}

async function stepTwo() {
  await stepThree();
}

async function stepOne() {
  await stepTwo();
}

stepOne().catch(console.error);

Because await points preserve promise chains, V8 reconstructs the full asynchronous call chain across ticks:

Error: Asynchronous failure!
    at stepThree (server.js:3:9)
    at async stepTwo (server.js:7:3)
    at async stepOne (server.js:11:3)

Note: Asynchronous stack reconstruction only works across async/await and native Promises. Raw callbacks (e.g. fs.readFile(path, (err, data) => ...) or setTimeout) break the async stack trace chain unless wrapped in Promises.


5. Source Map Support for TypeScript and Bundlers

When running transpiled code (TypeScript, Babel, esbuild, Webpack), stack traces report lines in the generated .js files rather than your original source files.

Node.js includes native source map support using the --enable-source-maps flag:

node --enable-source-maps dist/index.js

With this flag enabled, Node.js automatically consults inline or external .map files and maps stack traces back to original TypeScript filenames and line numbers:

Error: User not found
    at UserService.findById (/src/services/user.service.ts:42:13)
    at UserController.get (/src/controllers/user.controller.ts:18:25)

6. Security and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents