0
0
Expressframework~5 mins

HTTP caching headers (ETag, Cache-Control) in Express

Choose your learning style9 modes available
Introduction

HTTP caching headers help browsers and servers save time and data by reusing stored responses instead of downloading them again.

When you want to speed up your website by letting browsers reuse unchanged files.
When you want to reduce server load by avoiding sending the same data repeatedly.
When you want to control how long browsers keep your content before checking for updates.
When you want to ensure users see the latest version only when content changes.
When building APIs that return data which may not change often.
Syntax
Express
res.set('Cache-Control', 'public, max-age=3600');
res.set('ETag', 'unique-identifier');

Cache-Control tells browsers how long to keep the response (in seconds).

ETag is a unique ID for the response content to check if it changed.

Examples
This tells browsers not to store the response at all.
Express
res.set('Cache-Control', 'no-store');
This allows caching for 24 hours (86400 seconds).
Express
res.set('Cache-Control', 'public, max-age=86400');
This sets a fixed ETag value to identify the response version.
Express
res.set('ETag', '12345abcde');
Sample Program

This Express server sends JSON data with Cache-Control and ETag headers.

If the client sends the same ETag in If-None-Match, the server replies with 304 Not Modified, saving bandwidth.

Express
import express from 'express';
const app = express();

app.get('/data', (req, res) => {
  const data = { message: 'Hello, world!' };
  const jsonData = JSON.stringify(data);
  const etag = 'W/"' + Buffer.from(jsonData).toString('base64') + '"';

  res.set('Cache-Control', 'public, max-age=60');
  res.set('ETag', etag);

  if (req.headers['if-none-match'] === etag) {
    res.status(304).end();
  } else {
    res.json(data);
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

ETags help browsers know if content changed without downloading it again.

Cache-Control max-age is in seconds and controls how long to keep cached data.

Always test caching behavior using browser DevTools Network tab to see headers and responses.

Summary

HTTP caching headers improve website speed and reduce data usage.

Use Cache-Control to set how long browsers keep content.

Use ETag to identify content versions and avoid unnecessary downloads.