Universal JavaScript Stack Trace Library
stacktrace.js is a framework-agnostic micro-library designed to generate, parse, and enhance JavaScript stack traces across all environments, including browsers and Node.js. The current stable version is 2.0.2. It maintains a moderate release cadence, with updates typically addressing dependency bumps, bug fixes, and minor enhancements. Key differentiators include its ability to parse ES6 code, extensible StackFrame objects that report on constructor, native, or eval code, and its use of source maps for enhanced trace accuracy. It modularizes functionality into several sub-projects like error-stack-parser and stacktrace-gps to handle specific aspects of stack trace processing, providing both asynchronous (Promise-based) and synchronous API methods for flexibility. The library is particularly useful for robust error reporting and debugging applications.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'then')
cause Attempting to call `.then()` on the result of `StackTrace.getSync()`, which returns an Array, not a Promise.fixUse `StackTrace.get().then(...)` for asynchronous, Promise-based operations, or directly process the Array returned by `StackTrace.getSync()`. -
ReferenceError: StackTrace is not defined
cause The `StackTrace` global or imported object is not available in the current scope, often due to incorrect CommonJS `require` in an ESM context or missing import statement.fixEnsure you have `import * as StackTrace from 'stacktrace-js';` or `import { get, fromError } from 'stacktrace-js';` at the top of your ES module, or that the UMD bundle has been correctly loaded in a non-module environment. -
Error: Could not find a method to parse stack string.
cause This error might occur internally within `error-stack-parser` if the browser's `Error.stack` format is unusual or unrecognized, or if the `Error` object itself is malformed.fixEnsure the `Error` object passed to `StackTrace.fromError()` is a standard JavaScript Error instance. If the issue persists, it might indicate an environment-specific parsing limitation; consider reporting to the library's GitHub issues.
Warnings
- breaking Version 2.0.0 introduced breaking changes related to the `StackFrame` object, enhancing its extensibility. If you were directly manipulating or relying on specific internal structures of `StackFrame` instances prior to v2.0.0, you might need to adjust your code.
- gotcha The `StackTrace.getSync()` method does not enhance stack traces with source maps or guess anonymous function names. This means the trace will be less detailed and potentially harder to debug in production environments.
- breaking The project license changed from what was implied by earlier versions (likely Apache 2.0 or similar) to MIT License in v2.0.0, following a community vote. This is a legal breaking change that might affect compliance for some organizations.
- breaking Upgrading from 0.x to 1.x required significant changes due to modularization. The API surface changed dramatically as `stacktrace.js` was split into five separate projects (`stacktrace-gps`, `error-stack-parser`, `stack-generator`, `stackframe`).
Install
-
npm install stacktrace-js -
yarn add stacktrace-js -
pnpm add stacktrace-js
Imports
- StackTrace
const StackTrace = require('stacktrace-js');import * as StackTrace from 'stacktrace-js'; // or import { get, fromError, instrument, getSync, generateArtificially } from 'stacktrace-js'; - StackFrame
import { StackFrame } from 'stacktrace-js';import { StackFrame } from 'stackframe'; - fromError
StackTrace.fromError(error); // This works after a namespace import, but direct named import is preferred.
import { fromError } from 'stacktrace-js';
Quickstart
import { get, fromError } from 'stacktrace-js';
async function captureAndLogStackTraces() {
try {
// Simulate an error to capture its stack
let simulatedError = new Error('This is a simulated error for demonstration.');
const stackframesFromError = await fromError(simulatedError);
console.log('--- Stack trace from Error object ---');
console.log(stackframesFromError.map(sf => sf.toString()).join('\n'));
// Get the stack trace from the current execution point
const stackframesCurrent = await get();
console.log('\n--- Stack trace from current location ---');
console.log(stackframesCurrent.map(sf => sf.toString()).join('\n'));
} catch (err: any) {
console.error('Failed to get stack trace:', err.message);
}
}
captureAndLogStackTraces();
// Example of synchronous usage (without source map resolution)
import { getSync } from 'stacktrace-js';
function callSynchronousTrace() {
console.log('\n--- Synchronous Stack trace (no source maps) ---');
const syncStackframes = getSync();
console.log(syncStackframes.map(sf => sf.toString()).join('\n'));
}
callSynchronousTrace();