Menu

Post image 1
Post image 2
1 / 2
0

5 Express.js Middleware Patterns You'll Use in Every App

DEV Community·Alex Chen·17 days ago
#jtoNckYt
#pattern#backend#javascript#node#const#error
Reading 0:00
15s threshold

5 Express.js Middleware Patterns You'll Use in Every App Middleware is Express's superpower. These 5 patterns cover 90% of what you need. What Is Middleware? Request → [Middleware 1] → [Middleware 2] → [Middleware 3] → Response ↓ ↓ ↓ Log auth Parse body Handle error Each middleware can: - Modify request (req) or response (res) - End the response (res.send()) - Pass control to next middleware (next()) - Throw an error (next(err)) Enter fullscreen mode Exit fullscreen mode Pattern 1: Request Validation Middleware // ❌ Validation scattered in every route: app . post ( ' /api/users ' , async ( req , res ) => { if ( ! req . body . email ) return res . status ( 400 ). json ({ error : ' email required ' }); if ( ! isValidEmail ( req . body . email )) return res . status ( 400 ). json ({ error : ' invalid email ' }); if ( ! req . body . name || req . body . name . length > 100 ) return res . status ( 400 ). json ({ error : ' invalid name ' }); // ...…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More