How to Set Custom Response Headers in Express.js

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Express.js, a minimal and flexible Node.js web application framework, provides a robust set of features to develop web and mobile applications with ease. One of the flexible features of Express.js is its ability to manipulate HTTP response headers which are sent to the client.

In this tutorial, we will explore how to set custom HTTP response headers in Express.js. Understanding how to manipulate these headers can help in various scenarios such as setting security policies, handling CORS (Cross-Origin Resource Sharing), and controlling cache behaviors.

Setting Basic Custom Headers

To set a custom header, we can use the response.set() method. Below is a basic example:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.set('Custom-Header', 'HeaderValue');
  res.status(200).send('Custom header set');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Setting Multiple Headers

To set multiple headers at once, you can pass an object to the response.set() method like this:

app.get('/multiple', (req, res) => {
  res.set({
    'Header-One': 'ValueOne',
    'Header-Two': 'ValueTwo'
  });
  res.status(200).send('Multiple headers set');
});

Dynamic Headers with Request Data

Sometimes, setting headers dynamically based on request data may be necessary. The following example illustrates this:

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.set('User-ID', userId);
  res.status(200).send(`User header set for ID: ${userId}`);
});

Using Middleware to Set Headers

For setting headers across multiple routes, a custom middleware function is efficient:

function setCustomHeaders(req, res, next) {
  res.set('X-Custom-Header', 'CustomValue');
  next();
}

app.use(setCustomHeaders);

// Now all the responses in routes defined after this middleware will have the X-Custom-Header set.

Setting Security Headers

Implementing HTTP security headers is an important practice for protecting your app against common security threats. Here’s an example:

app.use((req, res, next) => {
  res.set({
    'Content-Security-Policy': "default-src 'self'",
    'X-Content-Type-Options': 'nosniff',
    'X-Frame-Options': 'DENY'
  });
  next();
});

Conclusion

In this tutorial, we covered the basics of setting custom HTTP response headers in Express.js. We looked at setting individual and multiple headers, using headers to communicate with clients dynamically, utilizing middleware for global header settings, and implementing security headers. By applying these techniques, you can tailor your Express.js responses to meet various application requirements and enhance security.

As a best practice, always keep in mind the implications of exposing certain headers and ensure that no sensitive information is shared unintentionally. With these tools in hand, you’ll be well on your way to mastering response header manipulation in Express.js.