How to Create Auth Middleware in Express: Simple Guide
To create auth middleware in Express, define a function that checks user credentials or tokens from the request, then call
next() if valid or respond with an error if not. Use app.use() or route-specific middleware to apply it.Syntax
An Express middleware function has three parameters: req (request), res (response), and next (to pass control). The auth middleware checks authentication and calls next() to continue or sends a response to stop.
- req: Contains request data like headers and body.
- res: Used to send responses back to the client.
- next: Moves to the next middleware or route handler.
javascript
function authMiddleware(req, res, next) { // Check authentication here if (req.headers.authorization === 'secret-token') { next(); // User is authenticated } else { res.status(401).send('Unauthorized'); // Stop request } }
Example
This example shows a simple Express app with auth middleware protecting a route. The middleware checks for a specific token in the Authorization header and allows access only if it matches.
javascript
import express from 'express'; const app = express(); function authMiddleware(req, res, next) { const token = req.headers.authorization; if (token === 'secret-token') { next(); } else { res.status(401).send('Unauthorized'); } } app.get('/protected', authMiddleware, (req, res) => { res.send('Welcome to the protected route!'); }); app.get('/', (req, res) => { res.send('Public route, no auth needed.'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when creating auth middleware include:
- Not calling
next()when authentication succeeds, causing the request to hang. - Sending multiple responses by calling
res.send()and thennext(). - Not properly checking the token or credentials, allowing unauthorized access.
- Applying middleware globally when only some routes need protection.
javascript
function wrongAuth(req, res, next) { if (req.headers.authorization === 'secret-token') { res.send('Authorized'); next(); // Wrong: calling next after sending response } else { res.status(401).send('Unauthorized'); } } // Correct way: function correctAuth(req, res, next) { if (req.headers.authorization === 'secret-token') { next(); // Proceed to next handler } else { res.status(401).send('Unauthorized'); } }
Quick Reference
Tips for auth middleware in Express:
- Always call
next()if authentication passes. - Send a response only if authentication fails.
- Use
req.headers.authorizationor cookies to get credentials. - Apply middleware only to routes that need protection.
- Keep middleware simple and focused on auth logic.
Key Takeaways
Create auth middleware as a function with req, res, and next parameters.
Call next() only when the user is authenticated to continue processing.
Send a 401 Unauthorized response if authentication fails.
Apply middleware to routes that require protection, not globally by default.
Avoid sending multiple responses or forgetting to call next().