How to Set Response Headers in Express

Jul 9, 2024

Express' response object, commonly called res, has a set() function that sets a response header. For example, the following code sets the Content-Type header in an Express route handler.

app.get('/hello', function routeHandler(req, res) {
  res.set('Content-Type', 'text/plain');

  res.end('Hello, World');
});

To set a response header for multiple routes, you can use Express middleware. Just make sure you call app.use() to register your Express middleware before your route handlers.

// Sets `Content-Type` response header on *all** responses
app.use(function myMiddleware(req, res, next) {
  res.set('Content-Type', 'text/plain');
  next();
});

app.get('/hello', function routeHandler(req, res) {
  // `myMiddleware` already executed when `routeHandler` runs
  res.end('Hello, World');
});

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials