0
0
ExpressHow-ToBeginner · 3 min read

How to Set Response Headers in Express: Simple Guide

In Express, you set response headers using the res.set() or res.header() methods inside your route handlers. These methods accept either a header name and value or an object with multiple headers to send custom HTTP headers to the client.
📐

Syntax

Use res.set(name, value) or res.set(object) to set HTTP headers on the response. name is the header field name as a string, and value is the header value. You can also pass an object with multiple headers.

javascript
res.set('Content-Type', 'application/json');
// or
res.set({ 'Cache-Control': 'no-cache', 'X-Custom-Header': 'value' });
💻

Example

This example shows how to set custom headers in an Express route before sending a JSON response.

javascript
import express from 'express';
const app = express();

app.get('/data', (req, res) => {
  res.set({
    'Content-Type': 'application/json',
    'Cache-Control': 'no-store',
    'X-Powered-By': 'Express'
  });
  res.send({ message: 'Hello, world!' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When you visit http://localhost:3000/data, the response headers include Content-Type, Cache-Control, and X-Powered-By with the JSON body.
⚠️

Common Pitfalls

  • Setting headers after calling res.send() or res.end() will not work because the response is already sent.
  • Using res.header() is an alias for res.set(), but mixing them can confuse readers.
  • Headers names are case-insensitive but use standard casing for clarity (e.g., Content-Type).
javascript
/* Wrong: setting header after sending response */
app.get('/wrong', (req, res) => {
  res.send('Done');
  res.set('X-Test', 'value'); // This will be ignored
});

/* Right: set headers before sending response */
app.get('/right', (req, res) => {
  res.set('X-Test', 'value');
  res.send('Done');
});
📊

Quick Reference

MethodDescriptionUsage Example
res.set(name, value)Sets a single headerres.set('Content-Type', 'text/html')
res.set(object)Sets multiple headers at onceres.set({ 'Cache-Control': 'no-cache', 'X-Test': '123' })
res.header(name, value)Alias for res.set()res.header('Content-Type', 'application/json')
res.get(name)Gets a header valueconst val = res.get('Content-Type')

Key Takeaways

Always set response headers before sending the response body with res.send or res.end.
Use res.set() or res.header() to add or modify HTTP headers in Express responses.
You can set multiple headers at once by passing an object to res.set().
Header names are case-insensitive but use standard casing for readability.
Avoid setting headers after the response is sent, as they will be ignored.