Headers and Cookies
Headers carry metadata. Set-Cookie stores a cookie in the browser, and the Cookie header sends it back. Use HttpOnly and Secure flags for session cookies.
Example
const http = require('node:http');
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', 'sid=abc123; HttpOnly; Path=/');
res.setHeader('X-App', 'demo');
res.end(req.headers['user-agent'] ? 'ua' : 'no ua');
});
server.listen(0, async () => {
const r = await fetch(`http://localhost:${server.address().port}`);
console.log(r.headers.get('x-app'), r.headers.get('set-cookie'));
server.close();
});Result
demo sid=abc123; HttpOnly; Path=/
Exercise
Set a response header.
res.("X-A", "1")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.