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');
});

Built an Express app and want to deploy it?

We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.

Deploy your Express app on Railway in minutes

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

More Express Tutorials