First, install Express.js if you haven't already:
npm install express
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Node.js Middleware Tutorial!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Run the server with:
node server.js
Middleware functions take three arguments:
req
(request)res
(response)next
(function to move to the next middleware)Add a simple logging middleware before routes:
const logger = (req, res, next) => {
console.log(`${req.method} request to ${req.url}`);
next(); // Move to the next middleware or route
};
app.use(logger);
Express provides built-in middleware like express.json()
for parsing JSON data:
app.use(express.json()); // Parses incoming JSON requests
Example POST route:
app.post('/data', (req, res) => {
res.json({ received: req.body });
});
You can install third-party middleware for additional features. Example: cors
to allow cross-origin requests.
Install cors
:
npm install cors
Use it in your app:
const cors = require('cors');
app.use(cors()); // Enables cross-origin requests
Middleware can be used for user authentication before reaching protected routes.
const authenticate = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(403).json({ error: 'Access Denied' });
next(); // Proceed to the next middleware/route
};
app.get('/protected', authenticate, (req, res) => {
res.send('Welcome to the protected route!');
});
A global error handler catches all errors and prevents app crashes:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send({ error: 'Something went wrong!' });
});
Middleware is an essential part of Express.js for handling requests, authentication, logging, and error handling. This guide covered:
✅ Creating custom middleware
✅ Using built-in middleware
✅ Implementing authentication middleware
✅ Using third-party middleware like cors
✅ Handling errors with global middleware
Now, you can enhance your Express.js applications with middleware to improve security, performance, and flexibility! 🚀