Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: set explicit browser cache headers (#10614)

Dylan Madisetti3f76d9d30c4d
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index bf01597c65..44e30da009 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import hashlib
import mimetypes
import re
from pathlib import Path
@@ -141,6 +142,33 @@ _HTML_SECURITY_HEADERS: dict[str, str] = {
}
+def _html_response(request: Request, html: str) -> Response:
+ """Return rendered HTML with conditional caching headers."""
+ etag = f'"{hashlib.sha256(html.encode("utf-8")).hexdigest()}"'
+ # The document inlines per-server config and a notebook key. Browsers may
+ # store it, but must check that it is still current before reusing it.
+ cache_control = "private, no-cache"
+ headers = {
+ "Cache-Control": cache_control,
+ "ETag": etag,
+ **_HTML_SECURITY_HEADERS,
+ }
+
+ if_none_match = request.headers.get("if-none-match")
+ if if_none_match is not None:
+ # If-None-Match may contain multiple validators or weak ETags (`W/`).
+ # See https://www.rfc-editor.org/rfc/rfc9110#section-13.1.2
+ candidates = {
+ candidate.strip().removeprefix("W/")
+ for candidate in if_none_match.split(",")
+ }
+ # Allow caching if things exactly match.
+ if "*" in candidates or etag in candidates:
+ return Response(status_code=304, headers=headers)
+
+ return HTMLResponse(html, headers=headers)
+
+
def _strip_access_token_redirect(request: Request) -> RedirectResponse:
"""Build a redirect to the current URL with access_token removed.
@@ -418,7 +446,7 @@ async def index(request: Request) -> Response:
# Inject service worker registration with the notebook ID
html = _inject_service_worker(html, file_key)
- return HTMLResponse(html, headers=_HTML_SECURITY_HEADERS)
+ return _html_response(request, html)
DEFAULT_NOTEBOOK_NAME = "__marimo_notebook__.py"
diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.py
index 389ef16c23..87fbd7e5de 100644
--- a/tests/_server/api/endpoints/test_assets.py
+++ b/tests/_server/api/endpoints/test_assets.py
@@ -26,6 +26,7 @@ from marimo._server.workspace import (
from marimo._session.model import SessionMode
from marimo._utils.http import HTTPException
from marimo._utils.marimo_path import MarimoPath
+from tests._server.conftest import get_user_config_manager
from tests._server.mocks import (
token_header,
with_workspace,
@@ -214,6 +215,55 @@ def test_index_response_has_security_headers(client: TestClient) -> None:
assert response.headers.get("x-content-type-options") == "nosniff"
+def test_index_response_revalidates_with_etag(client: TestClient) -> None:
+ response = client.get("/", headers=token_header())
+ assert response.status_code == 200, response.text
+ assert response.headers["cache-control"] == "private, no-cache"
+ etag = response.headers["etag"]
+
+ response = client.get(
+ "/",
+ headers={**token_header(), "If-None-Match": etag},
+ )
+ assert response.status_code == 304
+ assert response.content == b""
+ assert response.headers["cache-control"] == "private, no-cache"
+ assert response.headers["etag"] == etag
+
+
+def test_index_response_accepts_weak_etag(client: TestClient) -> None:
+ response = client.get("/", headers=token_header())
+ etag = response.headers["etag"]
+
+ response = client.get(
+ "/",
+ headers={
+ **token_header(),
+ "If-None-Match": f'"other", W/{etag}',
+ },
+ )
+ assert response.status_code == 304
+
+
+def test_index_etag_changes_with_config(client: TestClient) -> None:
+ response = client.get("/", headers=token_header())
+ etag = response.headers["etag"]
+
+ config_manager = get_user_config_manager(client)
+ config = config_manager.get_config()
+ config["display"]["theme"] = (
+ "dark" if config["display"]["theme"] != "dark" else "light"
+ )
+ config_manager.save_config(config)
+
+ response = client.get(
+ "/",
+ headers={**token_header(), "If-None-Match": etag},
+ )
+ assert response.status_code == 200
+ assert response.headers["etag"] != etag
+
+
def test_index_with_directory(client: TestClient, tmp_path: Path) -> None:
with workspace_scope(
client, DirectoryWorkspace(str(tmp_path), include_markdown=False)