0
0
Expressframework~5 mins

Conditional requests handling in Express

Choose your learning style9 modes available
Introduction

Conditional requests help your server save work by sending data only if it has changed. This makes websites faster and uses less internet data.

When you want to avoid sending the same data again if the client already has the latest version.
When building APIs that return resources which might not change often.
When you want to improve performance by reducing unnecessary data transfer.
When handling browser caching to make pages load faster.
When you want to support HTTP caching headers like ETag or Last-Modified.
Syntax
Express
app.get('/resource', (req, res) => {
  res.set('ETag', 'abc123');
  if (req.fresh) {
    res.status(304).end();
  } else {
    res.send('Your data here');
  }
});

req.fresh is true if the client's cached version is up to date.

Sending status 304 Not Modified tells the client to use its cached data.

Examples
This example uses an ETag header to help the client check if data changed.
Express
app.get('/data', (req, res) => {
  res.set('ETag', '12345');
  if (req.fresh) {
    res.status(304).end();
  } else {
    res.send('Hello World');
  }
});
This example uses Last-Modified header to tell when data was last changed.
Express
app.get('/info', (req, res) => {
  res.set('Last-Modified', new Date().toUTCString());
  if (req.fresh) {
    res.status(304).end();
  } else {
    res.send('Info data');
  }
});
Sample Program

This server sends a message with an ETag header. If the client sends the same ETag back, the server replies with 304 Not Modified, saving bandwidth.

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

app.get('/message', (req, res) => {
  const message = 'Hello from server!';
  const etag = 'v1';

  res.set('ETag', etag);

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

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

Always set ETag or Last-Modified headers to enable conditional requests.

Use req.fresh or check if-none-match and if-modified-since headers to decide if data changed.

Responding with 304 means no body is sent, so the client uses cached data.

Summary

Conditional requests help reduce data sent by checking if client cache is fresh.

Use ETag or Last-Modified headers to support conditional requests.

Respond with 304 status to tell client to use cached data.