0
0
Expressframework~5 mins

res.set for response headers in Express

Choose your learning style9 modes available
Introduction

res.set lets you add or change headers in the response your server sends. Headers give extra info about the response.

When you want to tell the browser what type of content you are sending, like JSON or HTML.
When you need to add security info, like telling browsers to only use HTTPS.
When you want to control caching so browsers know when to save or refresh data.
When you want to set cookies or custom info for the client.
When you want to specify language or encoding for the response.
Syntax
Express
res.set(field, value)
// or
res.set(object)

You can set one header by giving a field name and value.

Or set many headers at once by passing an object with key-value pairs.

Examples
Sets the Content-Type header to tell the client the response is JSON.
Express
res.set('Content-Type', 'application/json')
Sets multiple headers at once using an object.
Express
res.set({
  'Cache-Control': 'no-cache',
  'X-Powered-By': 'Express'
})
Sample Program

This Express app sets headers before sending a plain text response. It shows how to use res.set with both single and multiple headers.

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

app.get('/', (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.set({
    'X-Custom-Header': 'MyValue',
    'Cache-Control': 'no-store'
  });
  res.send('Hello, headers set!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Headers must be set before sending the response body with res.send or res.json.

Header names are case-insensitive but usually written in standard format like 'Content-Type'.

Using res.set does not send the response immediately; it just prepares headers.

Summary

res.set adds or changes headers in the HTTP response.

You can set one header or many at once using an object.

Always set headers before sending the response body.