Table Of Contents
Problem
You need to add custom headers like API version, server information, or security headers to all responses in your Express.js application without repeating code in every route.
Solution
const express = require('express');
const app = express();
// Middleware to add custom headers to all responses
app.use((req, res, next) => {
res.setHeader('X-API-Version', '1.0.0');
res.setHeader('X-Server', 'Node.js Express');
res.setHeader('X-Response-Time', new Date().toISOString());
// Security headers
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
next(); // Important: call next() to continue to the next middleware/route
});
// Your routes
app.get('/api/users', (req, res) => {
res.json({ users: ['John', 'Jane'] });
});
app.get('/api/posts', (req, res) => {
res.json({ posts: ['Post 1', 'Post 2'] });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
For multiple headers at once:
app.use((req, res, next) => {
res.set({
'X-API-Version': '1.0.0',
'X-Server': 'Node.js Express',
'X-Response-Time': new Date().toISOString()
});
next();
});
Explanation
Middleware functions execute for every request when placed before your routes. res.setHeader()
adds individual headers, while res.set()
accepts an object to set multiple headers efficiently.
Always call next()
to pass control to the next middleware or route handler. These headers will appear in all responses, making them perfect for consistent API metadata or security headers.
Share this article
Add Comment
No comments yet. Be the first to comment!