Sling Academy
Home/Node.js/How to Set Custom Response Headers in Express.js

How to Set Custom Response Headers in Express.js

Last updated: December 28, 2023

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.

Next Article: Express.js vs Nest.js: Which is better to build backend APIs?

Previous Article: Node.js: Get domain, hostname, and protocol from a URL

Series: The First Steps to Node.js

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates