CLSkills
April 10, 2026Samarth at CLSkills

How to Use Claude for Debugging — The /debug Protocol That Saves 2 Hours Every Time

The exact /debug template for Claude: EXPECTED, ACTUAL, ERROR, CODE, TRIED. Real debugging examples that save hours of frustrating troubleshooting.

claudedebuggingprogrammingdeveloper toolscoding
📬

Get notified when we discover new Claude codes

We test new prompt commands every week. Join 4+ developers getting them in their inbox.

How to Use Claude for Debugging — The /debug Protocol That Saves 2 Hours Every Time

You have been staring at this bug for an hour. You have re-read the same 50 lines of code six times. You have added console.logs everywhere. You have Googled the error message and found a Stack Overflow thread from 2019 that is close but not quite your problem. You are about to start randomly changing things to see what happens.

Stop. There is a better way.

The /debug protocol is a structured format for presenting bugs to Claude that consistently produces accurate diagnoses. It works because it forces you to organize the information Claude needs — and that organization alone sometimes reveals the bug before Claude even responds.

The /debug Template

Copy this template. Save it somewhere you can grab it fast. Every time you hit a bug that survives 15 minutes of manual debugging, fill this in and paste it into Claude.

/debug

**EXPECTED:** What should happen
[Describe the correct behavior in 1-2 sentences]

**ACTUAL:** What actually happens
[Describe the incorrect behavior. Be specific — "it doesn't work" is not helpful. "The function returns null instead of the user object when the email contains a plus sign" is helpful.]

**ERROR:** Error message (if any)
[Paste the full error message, stack trace, or console output. Include ALL of it — the line you think is irrelevant is often the clue.]

**CODE:** The relevant code
[Paste the code. Include more context than you think is necessary — the function that calls the broken function, the data model, the config. When in doubt, include it.]

**TRIED:** What you have already attempted
[List what you have tried so Claude does not suggest things you already ruled out]

**ENVIRONMENT:**
- Language/framework: [e.g., Python 3.11, Django 5.0]
- OS: [e.g., Ubuntu 22.04]
- Database: [if relevant]
- Recent changes: [What did you change right before it broke?]

Each section exists for a specific reason. Let me break down why this format works so well.

Why Each Section Matters

EXPECTED vs ACTUAL creates the gap. Claude needs to understand not just what is happening, but what should be happening. Without EXPECTED, Claude might "fix" your code in a way that solves the error but produces the wrong result.

ERROR gives Claude the stack trace, which is often the fastest path to a diagnosis. Full stack traces are better than partial ones. Claude Opus 4.6 can follow a stack trace through multiple files and identify the root cause even when the error surfaces far from the actual bug.

CODE is obvious, but the common mistake is pasting too little. If your bug is in a function that takes a user object, paste the function AND the code that creates the user object. The bug is often in the handoff between components.

TRIED prevents wasted turns. If you have already confirmed the database connection works, say so. Otherwise Claude's first suggestion will be "check your database connection" and you lose a turn.

ENVIRONMENT catches version-specific issues. A function that works in Python 3.9 might break in 3.11 due to a deprecation. A query that works in PostgreSQL might fail in MySQL. Claude needs this context.

Real Example: The Silent Authentication Failure

Here is a real debugging session that demonstrates the power of the template.

/debug

EXPECTED: Users should be able to log in with their Google account. After OAuth callback, they should be redirected to /dashboard with an active session.

ACTUAL: The OAuth flow completes (I can see the callback hit in logs), but the user is redirected to /login instead of /dashboard. No error message is shown to the user. The session cookie is not set.

ERROR: No error in the application logs. The OAuth callback returns 302. Server logs show:
[2026-04-08 14:23:01] GET /auth/google/callback?code=4/0AX4... 302
[2026-04-08 14:23:01] GET /dashboard 302
[2026-04-08 14:23:01] GET /login 200

CODE:
// auth.js - OAuth callback handler
app.get('/auth/google/callback', async (req, res) => {
  try {
    const { code } = req.query;
    const tokens = await oauth2Client.getToken(code);
    const ticket = await oauth2Client.verifyIdToken({
      idToken: tokens.tokens.id_token,
      audience: process.env.GOOGLE_CLIENT_ID,
    });
    const payload = ticket.getPayload();
    
    let user = await User.findOne({ email: payload.email });
    if (!user) {
      user = await User.create({
        email: payload.email,
        name: payload.name,
        googleId: payload.sub,
      });
    }
    
    req.session.userId = user._id;
    res.redirect('/dashboard');
  } catch (err) {
    console.error('Auth error:', err);
    res.redirect('/login?error=auth_failed');
  }
});

// middleware.js - Auth check
const requireAuth = (req, res, next) => {
  if (!req.session.userId) {
    return res.redirect('/login');
  }
  next();
};

// Session config in app.js
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true },
  store: MongoStore.create({ mongoUrl: process.env.MONGO_URI }),
}));

TRIED:
- Verified Google Client ID and Secret are correct
- Confirmed the OAuth callback URL matches Google Console settings
- The tokens are being returned correctly (logged them)
- User is being created in the database
- Tested with multiple Google accounts

ENVIRONMENT:
- Node.js 20, Express 4.18
- MongoDB 7.0 with Mongoose
- Running on localhost:3000 during development
- Recently upgraded from Express 4.17 to 4.18

Claude's response identified the bug in seconds:

The problem is cookie: { secure: true } in your session configuration. You are running on localhost:3000, which is HTTP, not HTTPS. When secure: true, the browser refuses to send the cookie over an insecure connection. The session is created server-side (which is why you see the user in the database), but the cookie never makes it to the browser, so the next request has no session.

Fix: Change to cookie: { secure: process.env.NODE_ENV === 'production' } so secure cookies are only enforced in production where you have HTTPS.

This is a bug that could take hours to find manually because there is no error. The OAuth works. The user is created. The session is set server-side. Everything looks correct — except the cookie silently fails to persist in the browser. The ENVIRONMENT detail about running on localhost was the key clue.

Advanced Debugging Prompts

When You Have No Error Message

Silent failures are the hardest bugs. Use this variation:

/debug — SILENT FAILURE

EXPECTED: [What should happen]
ACTUAL: [What happens instead — no error, just wrong behavior]

There is no error message or exception. The code runs without crashing but produces the wrong result.

CODE: [Paste code]

Please:
1. Trace the execution path step by step
2. At each step, state what you expect the value/state to be
3. Identify where the expected state diverges from what would produce the actual behavior
4. List the top 3 most likely root causes, ranked by probability

When the Bug Is Intermittent

/debug — INTERMITTENT

This bug happens approximately [FREQUENCY — e.g., "1 in 10 requests" or "only under high load" or "only on Mondays"].

EXPECTED: [Correct behavior]
ACTUAL: [Incorrect behavior when it fails]
ERROR: [Error when it fails, if any]

CODE: [Paste code]

Conditions when it fails: [Any patterns you have noticed]
Conditions when it works: [Describe normal operation]

Check specifically for:
- Race conditions or timing-dependent logic
- Shared mutable state
- Connection pool exhaustion
- Cache inconsistencies
- Timezone or locale-dependent behavior

When You Inherited the Codebase

/debug — UNFAMILIAR CODEBASE

I did not write this code and I am not fully familiar with how it works.

EXPECTED: [What the feature should do based on requirements/documentation]
ACTUAL: [What it currently does]
ERROR: [If any]

CODE: [Paste the relevant code — include more context than usual]

Please:
1. First, explain what this code does in plain English
2. Identify the likely intention of the original developer
3. Find where the code diverges from that intention
4. Suggest the minimal fix (do not refactor — just fix the bug)

The 15-Minute Rule

Here is the workflow that saves the most time:

  1. Hit a bug. Spend 15 minutes on your own first. Check the obvious things.
  2. If the bug survives 15 minutes, open Claude and fill in the /debug template.
  3. The act of filling in the template often reveals the bug (rubber duck debugging with structure).
  4. If it does not, submit to Claude. Read the diagnosis. Apply the fix.
  5. If the first suggestion does not work, reply with what happened and Claude adjusts.

The 15-minute cutoff is important. Less than that, you are reaching for AI too early and not building debugging instincts. More than that, you are burning time that Claude could save.

Claude Opus 4.6 is the stronger choice for complex, multi-file bugs. Sonnet 4.6 handles straightforward single-file issues perfectly and responds faster. For most debugging sessions, start with Sonnet and escalate to Opus if the first response misses the mark.

For the complete library of developer prompts including /debug variations, code review templates, and architecture analysis protocols, visit our prompt collection. Our cheat sheet has a printable version of the /debug template. And our complete guide covers all the protocols mentioned in this article in depth.

Stop Staring at Code

The next time you hit a bug, do not stare at it for two hours. Give it 15 minutes of honest effort, then open Claude and fill in the template: EXPECTED, ACTUAL, ERROR, CODE, TRIED, ENVIRONMENT. The structure alone makes you a better debugger, and Claude's analysis catches what tired eyes miss. Copy the template above, save it in your notes app, and use it the next time something breaks. You will wonder why you ever debugged any other way.

One email a week. Zero fluff.

New Claude Code skills, hidden prompt codes, and tested workflows — straight to your inbox. No spam, unsubscribe in 1 click.