How It Works Features Pricing Blog
Log In Start Free Trial
Express · JavaScript

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

TypeError: Cannot read properties of undefined (reading 'headers') at authMiddleware (/app/src/middleware/auth.js:5:22) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/app/node_modules/express/lib/router/index.js:328:13) at /app/node_modules/express/lib/router/index.js:286:9 at Function.process_params (/app/node_modules/express/lib/router/index.js:346:12) at next (/app/node_modules/express/lib/router/index.js:280:10) at expressInit (/app/node_modules/express/lib/middleware/init.js:40:5) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/app/node_modules/express/lib/router/index.js:328:13) at Function.handle (/app/node_modules/express/lib/router/index.js:167:3)

Here's what each line means:

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.

Before (broken)
function authMiddleware(req, res, next) {
  const token = req.headers.authorization;
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  next();
}

app.use(authMiddleware());
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm middleware processes requests correctly.
  2. Open a pull request with the middleware registration fix.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.