HTTP caching headers help browsers and servers save copies of files. This makes websites load faster and reduces internet data use.
0
0
HTTP caching headers in Node.js
Introduction
When you want your website images to load quickly for returning visitors.
When you want to reduce server load by letting browsers reuse files.
When you want to control how long browsers keep a copy of your webpage.
When you want to make sure users see updated content after changes.
When building APIs that return data which can be cached for some time.
Syntax
Node.js
res.setHeader('Cache-Control', 'public, max-age=3600')
Cache-Control is the main header to control caching behavior.
Use max-age to set how many seconds the file stays fresh.
Examples
This tells browsers to always check with the server before using a cached copy.
Node.js
res.setHeader('Cache-Control', 'no-cache')
This allows caching for 24 hours and lets any cache store the response.
Node.js
res.setHeader('Cache-Control', 'public, max-age=86400')
This caches the response only in the user's browser for 1 hour, not shared caches.
Node.js
res.setHeader('Cache-Control', 'private, max-age=3600')
This tells browsers and caches not to store the response at all.
Node.js
res.setHeader('Cache-Control', 'no-store')
Sample Program
This Node.js server sends a simple HTML page with a caching header that tells browsers to keep the page for 10 seconds before checking again.
Node.js
import http from 'node:http'; const server = http.createServer((req, res) => { if (req.url === '/') { res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'public, max-age=10'); res.end('<h1>Hello, caching!</h1>'); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
OutputSuccess
Important Notes
Setting caching headers properly improves website speed and reduces server work.
Use no-cache if content changes often and must be fresh.
Remember to test caching behavior using browser DevTools Network tab.
Summary
HTTP caching headers tell browsers how long to keep files.
Use Cache-Control with options like max-age, no-cache, and no-store.
Proper caching makes websites faster and saves data.