Skip to content

feat(static): add Last-Modified and ETag conditional caching - #269

Merged
pi0 merged 2 commits into
mainfrom
feat/static-caching-headers
Jul 17, 2026
Merged

feat(static): add Last-Modified and ETag conditional caching#269
pi0 merged 2 commits into
mainfrom
feat/static-caching-headers

Conversation

@pi0x

@pi0x pi0x commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds file-age and conditional-caching headers to serveStatic(). Every served file now carries Last-Modified and a weak ETag, and a conditional request that still matches is answered with an empty 304 Not Modified before the body is ever read.

  • Last-Modified from the file's mtime, floored to second granularity to match HTTP-date precision.
  • ETag — a weak validator (W/"<size>-<mtime>"). Weak because on-the-fly compression is not byte-stable and this middleware serves no byte ranges (the one advantage a strong tag would buy). The negotiated Content-Encoding is folded in, so a brotli and a gzip response under one URL get distinct validators — which a shared cache keying on Vary: Accept-Encoding relies on.
  • If-None-Match / If-Modified-Since304. If-None-Match takes precedence (RFC 9110 §13.2.2): present-and-unmatched is final, and If-Modified-Since is never consulted. The 304 carries ETag/Last-Modified/Vary but drops the representation headers.
  • The file handle is still opened (preserving the existing symlink-safety invariant), but the read stream and any compression are skipped for a 304.

Options

Two new options, both default true:

  • lastModified — emit Last-Modified and honor If-Modified-Since.
  • etag — emit ETag and honor If-None-Match.

renderHTML routes carry neither, since that body is the caller's to validate — consistent with how they are already excluded from compression.

Implementation notes

  • ServableFile now carries mtimeMs, pulled from the fstat openServable already performs — no extra syscall.
  • Validators are computed from the representation actually served (variant vs identity vs on-the-fly), so a client's echoed ETag always matches what it received.

Tests

14 new cases: weak-ETag shape, 304 round-trips for both validators, If-None-Match precedence over a fresh If-Modified-Since, per-encoding ETag distinctness (identity tag rejected on a gzip request), the etag: false / lastModified: false opt-outs, renderHTML exclusion, and conditional HEAD. All 125 static tests pass; lint and format clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Static file responses now include ETag and Last-Modified validators by default.
    • Supports conditional requests using If-None-Match and If-Modified-Since, returning 304 Not Modified when appropriate.
    • Added options to enable or disable either validator.
    • Validator handling supports compressed representations and HEAD requests.
  • Documentation

    • Expanded middleware guidance for static file caching and conditional requests.

Every served file now carries `Last-Modified` (from mtime) and a weak
`ETag`, and a matching `If-Modified-Since`/`If-None-Match` request is
answered with an empty `304 Not Modified` before the body is read.

- `If-None-Match` takes precedence over `If-Modified-Since` (RFC 9110
  §13.2.2): present-and-unmatched is final.
- The `ETag` is weak and folds in `Content-Encoding`, so brotli and gzip
  responses under one URL get distinct validators — which a cache keying
  on `Vary: Accept-Encoding` relies on. Weak because on-the-fly encodes
  are not byte-stable and no byte ranges are served.
- New `lastModified` and `etag` options (both default `true`).
- `renderHTML` routes carry neither: the rendered body is the caller's.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@pi0x
pi0x requested a review from pi0 as a code owner July 17, 2026 15:47
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@pi0x, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 37 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 04d15d8d-e002-46a0-9616-b3e808de30a1

📥 Commits

Reviewing files that changed from the base of the PR and between ed28708 and 121c400.

📒 Files selected for processing (3)
  • docs/1.guide/4.middleware.md
  • src/static.ts
  • test/static.test.ts
📝 Walkthrough

Walkthrough

Changes

Static cache validators

Layer / File(s) Summary
Validator generation and conditional response flow
src/static.ts
Adds configurable weak ETag and Last-Modified headers, encoded-representation support, conditional request precedence, and 304 Not Modified responses.
Documentation and behavioral coverage
docs/1.guide/4.middleware.md, test/static.test.ts
Documents validator options and verifies conditional requests, encodings, disabled validators, renderHTML, and HEAD behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • h3js/srvx#233: Directly overlaps with static-file validators and conditional 304 handling.
  • h3js/srvx#252: Covers encoded static representations and Vary behavior used by validator handling.

Suggested reviewers: pi0

Poem

A rabbit found validators bright,
ETags glowing softly at night.
“If unchanged,” they say,
“Send three-oh-four today!”
And files nap without a byte.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: static file conditional caching with Last-Modified and ETag support.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/static-caching-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 17, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/srvx@269

commit: 121c400

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/1.guide/4.middleware.md`:
- Line 112: Update the opening statement in the middleware documentation to
qualify that served files, excluding renderHTML routes, carry ETag and
Last-Modified headers. Keep the existing renderHTML clarification and all
validator behavior details unchanged.

In `@src/static.ts`:
- Around line 453-475: Update conditional request handling around
matchesIfNoneMatch: read the raw If-None-Match header regardless of etagValue,
let its presence suppress If-Modified-Since, and only evaluate the date
validator for GET/HEAD methods. For a matching If-None-Match, return 304 for
GET/HEAD and 412 for other configured methods; add coverage for ETag-disabled
requests with both headers and non-GET/HEAD behavior.
- Around line 446-449: Update the Last-Modified handling near lastModifiedMs to
clamp future file mtimes to the response origination time before converting them
to UTC. Preserve second-level precision and existing header behavior, and add a
regression test with a future-dated fixture verifying the emitted Last-Modified
is not in the future.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 48364c4b-00cc-4312-ab3f-8e602eb54894

📥 Commits

Reviewing files that changed from the base of the PR and between 6b3b291 and ed28708.

📒 Files selected for processing (3)
  • docs/1.guide/4.middleware.md
  • src/static.ts
  • test/static.test.ts

Comment thread docs/1.guide/4.middleware.md Outdated
Comment thread src/static.ts Outdated
Comment thread src/static.ts Outdated
@pi0 pi0 changed the title feat(static): add Last-Modified and ETag conditional caching feat(static): add Last-Modified and ETag conditional caching Jul 17, 2026
- Cap `Last-Modified` at the response origination time so a future/skewed
  file mtime cannot 304 an `If-Modified-Since` until real time catches up
  (RFC 9110 §8.8.2).
- Evaluate conditionals per RFC 9110 §13.2.2 precedence: a present
  `If-None-Match` suppresses `If-Modified-Since` regardless of the `etag`
  option (with ETags off, only `*` matches); a match answers GET/HEAD with
  `304` and any other configured method with `412`; `If-Modified-Since` is
  ignored for non-GET/HEAD (§13.1.3).
- Qualify the docs: validators cover files served without `renderHTML`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@pi0
pi0 merged commit 99ca81a into main Jul 17, 2026
15 checks passed
@pi0
pi0 deleted the feat/static-caching-headers branch July 17, 2026 16:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants