HTTP Response Freshness Testing

0.5.2 · maintenance · verified Tue Apr 21

The `fresh` package (version 0.5.2, last published in September 2017) is a minimalist Node.js utility designed to determine if an HTTP response is "fresh" according to client-provided caching headers. Part of the `jshttp` organization, which maintains foundational HTTP middleware and utilities leveraged by frameworks such as Express.js, this library compares a client's `If-None-Match` and `If-Modified-Since` request headers against a server's `ETag` and `Last-Modified` response headers. It returns `true` if the cached response is still valid, indicating a conditional GET request can result in a 304 Not Modified status, or `false` if the cache is stale and a full response is required. Its primary differentiators are strict adherence to HTTP specifications and a focused scope, prioritizing reliability for efficient conditional GET implementations. Given its mature and foundational nature, the package maintains a stable, maintenance-level release cadence with infrequent updates.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `fresh` function with example request and response headers to check HTTP cache freshness.

import fresh from 'fresh';

// Simulate a client request with caching headers
const requestHeaders = {
  'if-none-match': '"my-etag-v1"',
  'if-modified-since': new Date(Date.now() - 3600000).toUTCString() // 1 hour ago
};

// Simulate server response headers for a resource
const responseHeadersFresh = {
  'etag': '"my-etag-v1"',
  'last-modified': new Date().toUTCString()
};

const responseHeadersStale = {
  'etag': '"my-etag-v2"',
  'last-modified': new Date(Date.now() - 7200000).toUTCString() // 2 hours ago
};

// Check freshness against a fresh resource
const isFresh1 = fresh(requestHeaders, responseHeadersFresh);
console.log(`Is resource 1 fresh? ${isFresh1}`); // Expected: true

// Check freshness against a stale resource (different ETag)
const isFresh2 = fresh(requestHeaders, responseHeadersStale);
console.log(`Is resource 2 fresh? ${isFresh2}`); // Expected: false

// Simulate Cache-Control: no-cache from client
const requestHeadersNoCache = { ...requestHeaders, 'cache-control': 'no-cache' };
const isFreshNoCache = fresh(requestHeadersNoCache, responseHeadersFresh);
console.log(`Is resource fresh with no-cache? ${isFreshNoCache}`); // Expected: false (client forces revalidation)

view raw JSON →