debug:express
Debug Express.js and Node.js applications with systematic diagnostic techniques. This skill provides comprehensive guidance for troubleshooting middleware execution issues, routing problems, CORS errors, async error handling, memory leaks, and unhandled promise rejections. Covers DEBUG environment variable usage, Node Inspector with Chrome DevTools, VS Code debugging, Morgan request logging, and diagnostic middleware patterns. Includes four-phase debugging methodology and common error message reference.
What this skill does
# Express.js Debugging Guide
A systematic approach to debugging Express.js applications using proven techniques and tools.
## Common Error Patterns
### 1. Cannot GET /route (404 Errors)
**Symptoms:** Route returns 404, middleware not matching
**Common Causes:**
- Route not registered before catch-all handlers
- Missing leading slash in path
- Case sensitivity issues
- Router not mounted correctly
```javascript
// Wrong: catch-all before specific routes
app.use('*', notFoundHandler);
app.get('/api/users', getUsers); // Never reached
// Correct: specific routes before catch-all
app.get('/api/users', getUsers);
app.use('*', notFoundHandler);
```
### 2. Middleware Not Executing
**Symptoms:** Request hangs, next() not called, order issues
**Common Causes:**
- Forgetting to call `next()`
- Async middleware without proper error handling
- Wrong middleware order
```javascript
// Wrong: missing next()
app.use((req, res, next) => {
console.log('Request received');
// Hangs - next() never called
});
// Correct: always call next() or send response
app.use((req, res, next) => {
console.log('Request received');
next();
});
// Correct async middleware
app.use(async (req, res, next) => {
try {
await someAsyncOperation();
next();
} catch (err) {
next(err); // Pass error to error handler
}
});
```
### 3. CORS Errors
**Symptoms:** Browser blocks requests, preflight fails
**Common Causes:**
- CORS middleware placed after routes
- Missing OPTIONS handler
- Credentials not configured
```javascript
const cors = require('cors');
// Wrong: CORS after routes
app.get('/api/data', handler);
app.use(cors()); // Too late
// Correct: CORS before routes
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.get('/api/data', handler);
```
### 4. Async Error Handling
**Symptoms:** Unhandled promise rejections, app crashes
**Common Causes:**
- Missing try/catch in async handlers
- Promises not caught
- No global error handler
```javascript
// Wrong: unhandled async error
app.get('/users', async (req, res) => {
const users = await User.findAll(); // Throws, crashes app
res.json(users);
});
// Correct: wrap async handlers
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.findAll();
res.json(users);
}));
// Global error handler (must be last)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message
});
});
```
### 5. Memory Leaks
**Symptoms:** Heap growing, OOM errors, slow responses over time
**Common Causes:**
- Unclosed database connections
- Event listeners not removed
- Large objects in closures
- Global caches without limits
```javascript
// Wrong: unbounded cache
const cache = {};
app.get('/data/:id', (req, res) => {
cache[req.params.id] = largeObject; // Memory leak
});
// Correct: use LRU cache with limits
const LRU = require('lru-cache');
const cache = new LRU({ max: 500, ttl: 1000 * 60 * 5 });
// Check for leaks
node --inspect --expose-gc app.js
// Use Chrome DevTools Memory tab
```
### 6. Unhandled Promise Rejections
**Symptoms:** Warnings in console, silent failures
**Setup global handlers:**
```javascript
// Add to app entry point
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// Log to error tracking service
});
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
// Graceful shutdown
process.exit(1);
});
```
## Debugging Tools
### 1. DEBUG Environment Variable
The most powerful built-in debugging tool for Express.
```bash
# See all Express internal logs
DEBUG=express:* node app.js
# Specific areas only
DEBUG=express:router node app.js
DEBUG=express:application,express:router node app.js
# Multiple packages
DEBUG=express:*,body-parser:* node app.js
# Your own debug statements
DEBUG=myapp:* node app.js
```
```javascript
// In your code
const debug = require('debug')('myapp:server');
debug('Server starting on port %d', port);
```
### 2. Node Inspector (--inspect)
Start with Chrome DevTools support:
```bash
# Start with inspector
node --inspect app.js
# Break on first line
node --inspect-brk app.js
# Specific port
node --inspect=0.0.0.0:9229 app.js
```
Open `chrome://inspect` in Chrome, click "Open dedicated DevTools for Node".
### 3. VS Code Debugger
Create `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Express",
"program": "${workspaceFolder}/app.js",
"env": {
"DEBUG": "express:*",
"NODE_ENV": "development"
},
"console": "integratedTerminal"
},
{
"type": "node",
"request": "attach",
"name": "Attach to Process",
"port": 9229
}
]
}
```
### 4. Morgan Logger
HTTP request logging middleware:
```javascript
const morgan = require('morgan');
// Development: colored, concise
app.use(morgan('dev'));
// Production: Apache combined format
app.use(morgan('combined'));
// Custom format with response time
app.use(morgan(':method :url :status :response-time ms - :res[content-length]'));
// Log to file
const fs = require('fs');
const accessLogStream = fs.createWriteStream('./access.log', { flags: 'a' });
app.use(morgan('combined', { stream: accessLogStream }));
```
### 5. ndb Debugger
Enhanced debugging experience:
```bash
npm install -g ndb
ndb node app.js
```
Features: Better UI, async stack traces, blackbox scripts, profile recording.
### 6. ESLint for Prevention
Catch errors before runtime:
```bash
npm install eslint eslint-plugin-node --save-dev
npx eslint --init
```
```json
{
"extends": ["eslint:recommended", "plugin:node/recommended"],
"rules": {
"no-unused-vars": "error",
"no-undef": "error",
"node/no-missing-require": "error"
}
}
```
## The Four Phases (Express-specific)
### Phase 1: Reproduce and Isolate
1. **Get exact error message** - Check terminal, browser console, network tab
2. **Identify the route** - Which endpoint is failing?
3. **Check request details** - Method, headers, body, query params
4. **Minimal reproduction** - Can you trigger with curl/Postman?
```bash
# Test endpoint directly
curl -v http://localhost:3000/api/users
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"test"}' http://localhost:3000/api/users
```
### Phase 2: Gather Information
1. **Enable DEBUG logging**
```bash
DEBUG=express:* node app.js
```
2. **Add strategic logging**
```javascript
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
console.log('Headers:', req.headers);
console.log('Body:', req.body);
next();
});
```
3. **Check middleware order**
```javascript
app._router.stack.forEach((r, i) => {
if (r.route) {
console.log(`${i}: Route ${r.route.path}`);
} else if (r.name) {
console.log(`${i}: Middleware ${r.name}`);
}
});
```
4. **Inspect with breakpoints**
- Set breakpoint at route handler entry
- Step through middleware chain
- Inspect req/res objects
### Phase 3: Analyze and Hypothesize
1. **Check the stack trace** - Follow the call stack from error
2. **Verify assumptions**
- Is the route registered?
- Is middleware in correct order?
- Are environment variables set?
- Is database connected?
3. **Common culprits checklist:**
- [ ] Body parser before routes?
- [ ] CORS before routes?
- [ ] Auth middleware applied?
- [ ] Error handler at the end?
- [ ] Async errors caught?
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.