Performance: Setting response headers
Setting response headers affects how quickly the browser can start rendering content and how efficiently resources are cached or processed.
Jump into concepts and practice - no test required
const http = require('http'); http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'public, max-age=31536000'); res.end('<h1>Hello</h1>'); }).listen(3000);
const http = require('http'); http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'no-cache'); res.end('<h1>Hello</h1>'); }).listen(3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching headers or 'no-cache' | N/A | N/A | Blocks rendering until network response | [X] Bad |
| Proper Content-Type and long max-age caching | N/A | N/A | Allows fast rendering from cache | [OK] Good |
Content-Type to application/json in Node.js?Content-Type header sent to the client after running this code snippet?
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Type', 'application/json');
res.end('{}');
});
server.listen(3000);const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello');
res.setHeader('Content-Type', 'text/plain');
res.end();
});
server.listen(3000);Content-Type as application/json and Cache-Control as no-cache in a Node.js server. Which code snippet correctly sets both headers before sending the response?