Response headers tell the browser important information about the data it receives. Setting them helps control how the browser handles the response.
0
0
Setting response headers in Node.js
Introduction
When you want to tell the browser the type of content you are sending, like JSON or HTML.
When you want to allow or restrict access from other websites (CORS).
When you want to control caching behavior to make your site faster or always fresh.
When you want to set cookies or security policies for your site.
Syntax
Node.js
response.setHeader(name, value);
name is the header name as a string, like 'Content-Type'.
value is the header value as a string, like 'application/json'.
Examples
This tells the browser the response is HTML.
Node.js
response.setHeader('Content-Type', 'text/html');
This tells the browser not to cache the response.
Node.js
response.setHeader('Cache-Control', 'no-cache');
This allows any website to access the response (CORS).
Node.js
response.setHeader('Access-Control-Allow-Origin', '*');
Sample Program
This Node.js server sets two headers: it tells the browser the response is JSON and disables caching. Then it sends a JSON message.
Node.js
import http from 'node:http'; const server = http.createServer((request, response) => { response.setHeader('Content-Type', 'application/json'); response.setHeader('Cache-Control', 'no-store'); const data = { message: 'Hello, world!' }; response.end(JSON.stringify(data)); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
OutputSuccess
Important Notes
Headers must be set before sending the response body.
Header names are case-insensitive but usually written in standard capitalization.
Setting headers incorrectly can cause browsers to misinterpret your response.
Summary
Response headers give the browser important info about the response.
Use response.setHeader(name, value) to set headers in Node.js.
Always set headers before sending the response body.