Express JS response headers
In Express.js, response headers are used to provide additional information about the response, such as content type, cache control, or custom headers for security or other purposes. Setting response headers allows you to control how the client or browser interprets the response from the server.
Why Set Response Headers?
Headers help provide context for the response data and can manage aspects like:
- Content Type: Tell the client what type of content is being sent (e.g., JSON, HTML).
- Caching: Manage how long resources can be cached by the client.
- Security: Control how browsers handle your responses (e.g., restricting cross-origin requests).
- Custom Information: Add additional metadata to responses, like tracking IDs or server information.
Common Methods to Set Response Headers in Express.js
res.set()
(orres.header()
)res.type()
res.append()
1. Setting Headers with res.set()
(or res.header()
)
You can use res.set()
to set a single or multiple headers. This method allows you to define custom headers or set predefined ones like Content-Type
, Authorization
, etc.
Syntax:
res.set(field, value);
Example (Setting a Single Header):
app.get('/example', (req, res) => {
res.set('Content-Type', 'text/plain');
res.send('This is a plain text response.');
});
In this example, the Content-Type
header is explicitly set to text/plain
. This informs the client that the response body is plain text.
Example (Setting Multiple Headers):
app.get('/example', (req, res) => {
res.set({
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'X-Custom-Header': 'CustomValue'
});
res.json({ message: 'Hello World' });
});
In this case, multiple headers are set:
Content-Type: application/json
: Indicates the content being sent is JSON.Cache-Control: no-store
: Disables caching.X-Custom-Header
: Adds a custom header to the response.
2. Setting Content Type with res.type()
You can use res.type()
as a shorthand for setting the Content-Type
header.
Example:
app.get('/html', (req, res) => {
res.type('html');
res.send('<h1>This is an HTML response</h1>');
});
In this case, res.type('html')
sets the Content-Type
header to text/html
, signaling that the response is HTML content.
3. Appending Headers with res.append()
The res.append()
method is useful when you want to add a value to an existing header without overwriting the current value. It allows you to send multiple values for the same header (for example, when setting multiple Set-Cookie
headers).
Syntax:
res.append(field, value);
Example:
app.get('/cookies', (req, res) => {
res.append('Set-Cookie', 'userId=12345');
res.append('Set-Cookie', 'sessionToken=abcdef');
res.send('Cookies are set.');
});
This example sets multiple Set-Cookie
headers:
Set-Cookie: userId=12345
Set-Cookie: sessionToken=abcdef
4. Using Headers for Caching
You can control caching behavior using headers like Cache-Control
or Expires
.
Example:
app.get('/cache', (req, res) => {
res.set('Cache-Control', 'public, max-age=3600');
res.send('This response is cached for 1 hour.');
});
In this example, the Cache-Control
header is set to public, max-age=3600
, meaning that the response can be cached for 3600 seconds (1 hour).
5. Setting Security Headers
Security-related headers help protect your application from common vulnerabilities like XSS, clickjacking, etc. These headers can be added manually or using security middleware like helmet
.
Example (Manual Security Headers):
app.get('/secure', (req, res) => {
res.set('X-Frame-Options', 'DENY'); // Prevents clickjacking
res.set('X-Content-Type-Options', 'nosniff'); // Prevents MIME-type sniffing
res.set('Content-Security-Policy', "default-src 'self'"); // Prevents XSS attacks
res.send('This response has security headers.');
});
You can also use middleware like helmet to automate the setting of common security headers.
6. Sending Custom Headers
Custom headers can be set to pass metadata or other information with your response. These headers are usually prefixed with X-
.
Example:
app.get('/custom-header', (req, res) => {
res.set('X-Powered-By', 'ExpressJS');
res.set('X-App-Version', '1.0.0');
res.send('Custom headers sent.');
});
In this case, two custom headers are sent:
X-Powered-By: ExpressJS
X-App-Version: 1.0.0
Example Summary
Basic Example Setting Headers:
const express = require('express');
const app = express();
app.get('/headers', (req, res) => {
res.set({
'Content-Type': 'application/json',
'X-Custom-Header': 'MyValue',
'Cache-Control': 'no-cache'
});
res.status(200).json({ message: 'Headers set successfully!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This will send the following response headers:
Content-Type: application/json
X-Custom-Header: MyValue
Cache-Control: no-cache