Middleware in a Node.js API serves as a bridge between the request and response cycle. It allows you to add functionality like logging, authentication, and error handling, making your API more robust and easier to manage. Below are three diverse and practical examples of adding middleware in a Node.js API.
Logging middleware is useful for tracking requests made to your API. It can help you debug issues and monitor API usage. This middleware will log the HTTP method and URL of each request.
const express = require('express');
const app = express();
// Logging Middleware
app.use((req, res, next) => {
console.log(`Received ${req.method} request for '${req.url}'`);
next(); // Pass control to the next middleware or route
});
app.get('/api/data', (req, res) => {
res.json({ message: 'Here is your data!' });
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
winston
or morgan
for more advanced logging capabilities.Authentication middleware is crucial for securing your API. In this example, we’ll create a simple middleware that checks for a token in the request headers. If the token is missing or invalid, the request will be denied.
const express = require('express');
const app = express();
// Authentication Middleware
const authenticate = (req, res, next) => {
const token = req.headers['authorization'];
if (token && token === 'Bearer valid-token') {
next(); // Token is valid, proceed with the request
} else {
res.status(401).json({ message: 'Unauthorized' }); // Deny access
}
};
app.use(authenticate);
app.get('/api/protected', (req, res) => {
res.json({ message: 'This is protected data!' });
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
jsonwebtoken
for handling JWT (JSON Web Tokens).Error handling middleware is essential for gracefully managing errors that occur in your API. This example demonstrates how to create middleware that catches errors and sends a user-friendly response.
const express = require('express');
const app = express();
app.get('/api/error', (req, res, next) => {
const error = new Error('Something went wrong!');
next(error); // Pass the error to the error handling middleware
});
// Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack
res.status(500).json({ message: 'Internal Server Error' }); // Send a user-friendly message
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
These examples of adding middleware in a Node.js API illustrate how to enhance your API’s functionality and maintainability. By incorporating logging, authentication, and error handling, you can build a more robust application that serves your users effectively.