Debugging a JavaScript Error by Giving AI the Full Trace First

A programmer working at a laptop, debugging code

To debug a JavaScript or TypeScript error with an AI model, paste the exact error message, the full stack trace, the code at the lines the trace points to, and your runtime and compiler versions, then ask the model to explain the cause before it proposes a fix. Most bad AI debugging answers come from missing context: the model sees one line of code and guesses at the rest. The prompts below are organized by error type (runtime errors, TypeScript compiler errors, async failures and build or module errors) because each one needs different evidence.

Photo via Unsplash, released under CC0.

Two terms first. A runtime error is thrown while the code executes, in a browser or in Node.js, and comes with a stack trace. A compile-time error in TypeScript is reported by the type checker (tsc or your editor) before the code runs, and comes with a numeric code such as TS2322. They look similar in a terminal but call for different prompts.

The evidence an AI model needs

A model can only reason about what you show it, so the quality of the answer depends on the bundle you paste. Before writing any prompt, collect:

  1. The exact error text, copied, not retyped. Engine wording differs: per MDN’s reference for this error, V8 (Chrome, Edge, Node.js) says Cannot read properties of undefined (reading 'x'), while Safari says undefined is not an object (evaluating 'obj.x').
  2. The full stack trace, including frames from libraries. The first frame from your own code is usually where to look, but the frames above it explain how you got there.
  3. The code at the reported lines, plus the function that produced the bad value, not just the line that crashed.
  4. Environment: Node.js or browser version, TypeScript version, framework and bundler, and the relevant tsconfig.json options.
  5. What changed: a dependency bump, a refactor, a new input. “It worked yesterday” plus a diff is often enough to find the cause.
  6. What you already tried, so the model does not suggest it again.

If you transpile TypeScript, make sure the stack trace points at your .ts files rather than compiled output. Node.js has an --enable-source-maps flag that, per the Node.js CLI documentation, makes a best effort to report positions in the original source. A trace that points into a minified bundle gives the model almost nothing to work with.

A base prompt for any JS/TS error

This general prompt works for most errors and is the template the specialized prompts below build on.

I have a [JavaScript | TypeScript] error. Help me find the root cause.

Environment: [Node 22 / Chrome 130 / Bun ...], TypeScript [version],
framework [React / Next.js / Express / none], bundler [Vite / webpack / tsc].

<error>
[exact error message and full stack trace]
</error>

<code>
[file name + the function containing the failing line, and the
function that creates the value involved]
</code>

<context>
What changed recently: [...]
What I already tried: [...]
</context>

Work in this order:
1. Restate in one sentence what the error literally means.
2. Name the most likely root cause, citing the specific line(s).
3. List up to two alternative causes and what evidence would
   distinguish them (a console.log, a breakpoint, a type check).
4. Propose the smallest fix for the root cause, not a guard that hides
   the symptom. Show a diff.
5. Say what you are unsure about. If you need another file, ask for it
   instead of guessing its contents.

Step 1 catches misreadings early: if the model’s restatement is wrong, the rest will be too. Step 3 is there because the first hypothesis is often wrong, and a cheap experiment beats a confident guess. Step 4’s “not a guard” rule matters because the easiest AI fix for undefined is to sprinkle ?. everywhere, which stops the crash and moves the bug somewhere quieter. Step 5 gives the model permission to ask for missing code instead of inventing it. Our general guide on AI prompts for debugging a stack trace covers trace-reading in more depth across languages.

Runtime errors: TypeError, ReferenceError, RangeError

Runtime errors in JavaScript are objects with a name and a message, and MDN’s JavaScript error reference lists well over a hundred of them grouped by name. The ones developers hit most:

ErrorTypical meaningEvidence to give the model
TypeError: Cannot read properties of undefined (reading 'x')A value you expected to be an object is undefined or nullWhere the value comes from: API response, props, array lookup, find() result
TypeError: x is not a functionCalling something that is not callable: wrong import, typo, shadowed nameThe import statement and the export it targets
ReferenceError: x is not definedName not declared in scope, or code running where a global does not exist (e.g. window on the server)Where the code runs (server, browser, worker) and the declaration
ReferenceError: Cannot access 'x' before initializationUsing a let/const/class before its declaration runs; often a circular importThe import graph between the involved modules
RangeError: Maximum call stack size exceededUnbounded recursion, including a setter or effect that triggers itselfThe repeating frames in the trace
SyntaxError: Unexpected token in JSON.parseThe string is not valid JSON, often an HTML error pageThe first 200 characters of the raw response

Prompt: trace an undefined value to its source

The crash is "Cannot read properties of undefined (reading '[prop]')"
at [file:line]. Do not suggest optional chaining yet.

Trace backwards: list every place the variable [name] gets its value,
from the crash site up to where it is created. For each step, say
whether it could produce undefined and under what input. Then tell me
which one is the real origin and what the correct behaviour should be
there (throw, default, early return, fix the data).

<code>[crash site + callers + data source]</code>

Banning the easy guard forces the model to follow the data. Once you know the origin, you decide whether undefined is a legitimate state (then handle it explicitly) or a bug upstream (then fix it there).

TypeScript compiler errors

TypeScript compiler errors are layered, and the last line is usually the one that matters. The TypeScript handbook page on understanding errors explains that the first line states the top-level problem and each indented line below explains why, down to the most specific mismatch. When you paste only the first line, the model loses the most useful part.

Type '{ m: string[]; }' is not assignable to type '{ m: number[]; }'.
  Types of property 'm' are incompatible.
    Type 'string[]' is not assignable to type 'number[]'.
      Type 'string' is not assignable to type 'number'.

Prompt: explain and fix a type error

TypeScript [version] reports this error. tsconfig has: strict [on/off],
noUncheckedIndexedAccess [on/off], target [..], module [..].

<error>
[full multi-line error with TS code, e.g. TS2322]
</error>

<code>
[the failing line, plus the type/interface definitions involved and
the signature of any function being called]
</code>

1. Read the error chain bottom-up and tell me the exact mismatch.
2. Decide which side is wrong: the value, or the declared type.
   Explain your reasoning.
3. Fix it without using `any`, `as` casts, `// @ts-ignore` or the
   non-null assertion `!`, unless you explain why the type system
   cannot express the truth here.
4. If the fix changes a public type, list other call sites that may
   break.

Point 3 is the important one. AI models frequently “fix” type errors with a cast, which silences the compiler and keeps the bug. Point 2 matters because a type error is a disagreement between two things, and sometimes the declared type is what is out of date.

Include your compiler options because they change which errors appear. Per the TSConfig reference, strict turns on a family of checks including strictNullChecks and noImplicitAny; with strictNullChecks on, users.find(...) returns a type that includes undefined, which is the source of the common “is possibly ‘undefined'” error (TS18048). The separate noUncheckedIndexedAccess option, which is not part of strict, adds undefined to values read through index signatures. A model that assumes the wrong settings will give a fix that does not compile on your project.

Async errors and unhandled promise rejections

Async bugs are hard for AI models because the stack trace often starts at the event loop, not at your code. Symptoms include a function returning Promise { <pending> } instead of data, an error that appears in the console but is never caught, or values that are correct in one run and stale in the next.

I suspect an async bug. Symptom: [what happens vs what should happen].

<code>
[the async function(s), every caller up to the entry point, and any
event handler or useEffect involved]
</code>

Check specifically for:
- a missing `await` (including inside .map / .forEach callbacks)
- a promise created but never awaited or returned
- try/catch that cannot catch because the await is outside it
- Promise.all where one rejection should not cancel the rest
  (consider Promise.allSettled)
- race conditions: two requests resolving out of order
- React effects without cleanup that set state after unmount

For each issue you find, quote the line and explain the execution
order step by step. Then give the corrected code.

Asking for the execution order step by step makes the model reason about timing explicitly rather than pattern-matching on “add await”. It also gives you an explanation you can check against what you see in the debugger.

Build, module and environment errors

Module errors are rarely about the line of code that reports them; they are about configuration. Typical examples are ERR_REQUIRE_ESM, Cannot use import statement outside a module, Cannot find module or a path alias that works in the editor but not at runtime. Paste configuration, not just code:

Build/module error:

<error>[full output of the failing command]</error>

Command run: [e.g. node dist/index.js | npx tsx src/index.ts | vite build]
package.json: "type" = [..], relevant "exports"/"main" fields: [..]
tsconfig.json: module [..], moduleResolution [..], paths [..], outDir [..]
Versions: node [..], typescript [..], [failing package]@[version]

Explain which part of the toolchain raises this error and why. Give
the minimum configuration change. If two valid fixes exist (e.g.
switch to ESM vs keep CommonJS), compare them in two sentences each.

Be careful with package versions here. Libraries change their module format and exports between major versions, and a model may recommend an option or API that a newer release removed. Our post on why AI coding assistants keep suggesting deprecated APIs explains why this happens and how to prompt around it: state your versions and ask the model to flag anything it is unsure exists in them.

A worked example

This example is illustrative. A Node.js service crashes with TypeError: Cannot read properties of undefined (reading 'email') at sendWelcome. The relevant code:

async function getUser(id: string) {
  const res = await fetch(`${API}/users/${id}`);
  const body = await res.json();
  return body.data;
}

async function sendWelcome(id: string) {
  const user = await getUser(id);
  await mailer.send(user.email, "Welcome!");
}

A bare “fix this error” prompt tends to return user?.email, which stops the crash and sends no email, silently. With the “trace an undefined value” prompt, a good answer walks back through the chain: user comes from getUser, which returns body.data, which is undefined when the API answers with an error body (say a 404 with { "error": "not found" }), because fetch does not throw on HTTP error statuses. The real fix is in getUser:

async function getUser(id: string): Promise<User> {
  const res = await fetch(`${API}/users/${id}`);
  if (!res.ok) {
    throw new Error(`getUser ${id} failed: HTTP ${res.status}`);
  }
  const body = await res.json();
  if (!body.data) throw new Error(`getUser ${id}: response has no data`);
  return body.data as User;
}

Now the failure is loud and points at the actual cause. The remaining as User is a deliberate, explained cast at a trust boundary; validating the shape with a schema library would be stricter still.

Common mistakes when debugging with AI

  • Pasting only the first line of the error. For TypeScript, the last line of the chain is usually the useful one. For runtime errors, the trace tells the model which function to ask about.
  • Accepting the first fix that compiles. Casts, any, ! and blanket optional chaining make errors disappear without fixing anything. Ask “what would make this value correct?” instead of “how do I stop the error?”.
  • Letting the model guess unseen code. If the answer refers to a function you did not paste, it is inventing it. Paste it or tell the model to ask.
  • Pasting secrets. Stack traces and config files can include tokens, connection strings and internal hostnames. Redact them before pasting into any external tool.
  • Skipping the regression test. Once you have the cause, write a test that reproduces it. Our AI prompts for writing unit tests can turn the failing input into a test case in a minute.

If the bug turns out to belong to someone else’s code, the same evidence bundle makes a good issue. The prompts in our guide to writing bug reports developers can act on turn it into a report with reproduction steps.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top