Back to articles
Middleware Patterns in Express: Composition, Error Handling, and Auth

Middleware Patterns in Express: Composition, Error Handling, and Auth

via Dev.to WebdevYoung Gao

Your Express app has 40 middleware functions. Some run on every route. Some run on three. Nobody knows what order they execute. Time to fix that. The Middleware Pipeline Middleware executes in the order you register it. Think of it as a pipeline: request enters from the left, passes through each function, and the response flows back. Request -> Logger -> Auth -> Validate -> Handler -> Error Handler -> Response Request Timing Middleware function requestTimer (): RequestHandler { return ( req , res , next ) => { const start = process . hrtime . bigint (); res . on ( " finish " , () => { const ms = Number ( process . hrtime . bigint () - start ) / 1 e6 ; logger . info ({ method : req . method , path : req . path , status : res . statusCode , ms }); }); next (); }; } Auth Middleware with JWT function authenticate (): RequestHandler { return ( req , res , next ) => { const token = req . headers . authorization ?. split ( " " )[ 1 ]; if ( \ ! token ) return res . status ( 401 ). json ({ erro

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
2 views

Related Articles