Fix TypeError: Cannot read properties of undefined (reading 'headers') in Express
This error occurs when middleware tries to access req.headers but the request object is undefined, usually because middleware parameters are in the wrong order or a middleware function is invoked incorrectly. Fix it by ensuring your middleware uses the correct (req, res, next) signature and is passed as a reference, not called.
Reading the Stack Trace
Here's what each line means:
- at authMiddleware (/app/src/middleware/auth.js:5:22): The auth middleware at line 5 tries to read headers from the first argument, but the first argument is not the request object.
- at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5): Express invoked the middleware function, but the function signature does not match what Express passes.
- at expressInit (/app/node_modules/express/lib/middleware/init.js:40:5): Express initialization middleware ran correctly, so the issue is with the custom middleware definition.
Common Causes
1. Middleware function invoked instead of passed as reference
The middleware is called with parentheses, executing it immediately and passing the return value (undefined) to Express instead of the function itself.
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
next();
}
// Bug: calling authMiddleware() instead of passing it
app.use(authMiddleware());
2. Wrong parameter order in middleware
The middleware parameters are defined in the wrong order, so what should be req is actually res or next.
function authMiddleware(res, req, next) {
const token = req.headers.authorization; // res is actually req here
next();
}
3. Error middleware missing err parameter
An error-handling middleware is missing the err parameter, shifting all other parameters and making req undefined.
// Missing err as first parameter for error middleware
app.use((req, res, next) => {
// This is treated as regular middleware
console.log(req.headers); // Works fine here
});
// But if registered as error handler:
app.use((req, res, next) => {
// req is actually err, res is actually req
console.log(req.headers); // Fails if err is a string
});
The Fix
Pass the middleware function as a reference without calling it. Using authMiddleware instead of authMiddleware() lets Express invoke it with the correct (req, res, next) arguments.
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
next();
}
app.use(authMiddleware());
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
next();
}
app.use(authMiddleware);
Testing the Fix
const request = require('supertest');
const express = require('express');
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
next();
}
describe('authMiddleware', () => {
let app;
beforeEach(() => {
app = express();
app.use(authMiddleware);
app.get('/protected', (req, res) => {
res.json({ message: 'success' });
});
});
it('returns 401 when no authorization header is present', async () => {
const response = await request(app).get('/protected');
expect(response.status).toBe(401);
expect(response.body.error).toBe('Unauthorized');
});
it('allows request with authorization header', async () => {
const response = await request(app)
.get('/protected')
.set('Authorization', 'Bearer test-token');
expect(response.status).toBe(200);
expect(response.body.message).toBe('success');
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/middleware-invocation,git add src/app.js src/__tests__/auth.test.js,git commit -m "fix: pass authMiddleware as reference instead of invoking it",git push origin fix/middleware-invocation
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm middleware processes requests correctly.
- Open a pull request with the middleware registration fix.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify protected routes work in staging.
Frequently Asked Questions
BugStack tests the middleware with both authenticated and unauthenticated requests, verifies the correct function signature, and confirms the Express pipeline works end to end.
Fixes are delivered as pull requests with CI checks. Your team reviews middleware changes to ensure security logic is preserved before merging.
Use parentheses when your middleware is a factory function that returns a middleware, e.g., authMiddleware({ secret: 'key' }) returns (req, res, next) => {}.
Error-handling middleware must have four parameters: (err, req, res, next). Express uses the parameter count to distinguish error handlers from regular middleware.