Middleware ordering and auth
Framework lane: Express 5.x (Supertest required for integration test). Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import express from 'express';export function createApp(testPrincipal) { const app = express(); app.use('/staff', (req,res,next) => { if (!testPrincipal) return res.sendStatus(401); if (testPrincipal.role !== 'staff') return res.sendStatus(403); next(); }); app.get('/staff/stock', (req,res) => res.json({ count: 4 })); return app;}Expected behavior (not observed): In isolated tests, no principal should receive 401; role reader should receive 403; role staff should receive 200 and count 4. Do not deploy this fixed-principal example.
How it works
Authentication establishes identity; authorization evaluates permission. Put checks before protected side effects and enforce object access in services too. The example uses a fixed synthetic principal injected by a trusted test factory, not client headers or real authentication. Missing identity and insufficient permission are different cases. Trust proxy and forwarded headers require explicit deployment-specific review.
Practice the underlying idea without dependencies
function decision(principal, owner) { if (!principal) return 401; return principal.id === owner ? 200 : 403;}console.log(JSON.stringify([decision(null,'u1'),decision({id:'u2'},'u1'),decision({id:'u1'},'u1')]));Run node main.mjs in a disposable directory. Expected output:
[401,403,200]This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
A role from a request body or arbitrary header is not a trusted identity. Never let a successful role check replace ownership checks on individual records.
Apply it yourself
Write the allow/deny matrix for a user reading their own order, another user’s order, and a request without a principal.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Middleware ordering and auth — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Where should a protective middleware be registered?
What does an authenticated reader lacking staff permission receive here?
Why is the fixed principal not production authentication?