How to Serve Static Files with Caching Headers
In this guide, we serve a single-page app (an HTML page plus its JavaScript and CSS files) from a directory with ZIO HTTP, and we make browsers cache it correctly. By the end, the server sends the assets with a one-year Cache-Control lifetime, makes the browser check index.html on every use, and answers that check with an empty 304 Not Modified response when the file has not changed.
We start with Middleware.serveDirectory and read the headers it already sends, then add a fallback to index.html for the app's own paths, a handler aspect that sets Cache-Control, and a second one that answers conditional requests.
The Problem
Middleware.serveDirectory serves files with an ETag and a Last-Modified header, but it sends no Cache-Control header and it never answers 304 Not Modified. Without Cache-Control, a browser picks a freshness lifetime on its own from Last-Modified (RFC 9111 calls this heuristic freshness), so after a deploy some users keep running the old index.html for a while. When the browser does check the file again, it sends the stored ETag in an If-None-Match header, and the server sends the whole file anyway.
For example, a server that serves the assets directory as it is:
import java.io.File
import zio._
import zio.http._
object PlainStaticServer extends ZIOAppDefault {
val routes: Routes[Any, Response] =
Routes.empty @@ Middleware.serveDirectory(Path.empty / "assets", new File("site/assets"))
def run = Server.serve(routes).provide(Server.default)
}
A request that sends back the ETag the server gave out still gets 200 OK and the full body:
$ curl -i -H 'If-None-Match: W/"1a237a06ac2-54"' localhost:8080/assets/app.3f9a1c.js
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06ac2-54"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/javascript; charset=utf-8
date: Wed, 02 Dec 2026 16:51:51 GMT
content-length: 84
document.getElementById("app").textContent = "Showing " + window.location.pathname;
The library gives us the validators (ETag and Last-Modified); the caching policy and the 304 reply are ours to add. Both fit in two small handler aspects.
Prerequisites
Add ZIO HTTP to your build.sbt:
// ZIO HTTP server and client
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
The examples in this guide use these imports:
import java.io.File
import zio._
import zio.http._
The server serves a site directory from its working directory. Its layout follows what front-end build tools such as Vite produce: one index.html and an assets directory where every file name contains a hash of the file's content:
site
├── index.html
└── assets
├── app.3f9a1c.js
└── app.8d2e0b.css
index.html loads both assets by their hashed names:
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf</title>
<link rel="stylesheet" href="/assets/app.8d2e0b.css">
</head>
<body>
<div id="app"></div>
<script src="/assets/app.3f9a1c.js"></script>
</body>
</html>
This guide assumes you know how to define routes and apply middleware to them.
Serving the Assets Directory
Middleware.serveDirectory adds a GET route under a URL path and answers it with the file at the rest of the path, resolved inside a local directory. We serve site/assets under /assets:
val siteDir = new File("site")
val assets: Middleware[Any] =
Middleware.serveDirectory(Path.empty / "assets", new File(siteDir, "assets"))
Applied to an empty set of routes, the middleware is a whole static file server:
Server.serve(Routes.empty @@ assets).provide(Server.default)
A request for /assets/app.3f9a1c.js returns site/assets/app.3f9a1c.js:
$ curl -i localhost:8080/assets/app.3f9a1c.js
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06ac2-54"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/javascript; charset=utf-8
date: Wed, 02 Dec 2026 16:51:51 GMT
content-length: 84
document.getElementById("app").textContent = "Showing " + window.location.pathname;
Each file is served by Handler.fromFile, which sets these headers:
Content-Typecomes from the file extension; text types also get the JVM's default charset, which is UTF-8 from JDK 18 on.ETagis a weak entity tag made of the file's modification time and size in hexadecimal:1a237a06ac2is the time in milliseconds and54is 84 bytes.Last-Modifiedis the file's modification time.Accept-Ranges: bytestells the client that it may ask for part of the file with aRangeheader, which gets a206 Partial Contentreply.
Because the ETag comes from the modification time and the size, copying a new version of a file over the old one changes it, and so does touching the file without changing its content.
A path with no file behind it gets 404 Not Found, and the server logs the java.io.FileNotFoundException at the error level. A path that contains .. or names a directory gets 400 Bad Request:
$ curl -i localhost:8080/assets/missing.js
HTTP/1.1 404 Not Found
date: Wed, 02 Dec 2026 16:51:51 GMT
content-length: 0
Middleware.serveResources serves files from the classpath instead of a directory. A resource in a directory on the classpath is served the same way. A resource inside a jar gets the same ETag and Last-Modified headers, built from the jar entry's time and size, but Accept-Ranges: none and no Range support.
How to Upload and Download Large Files with Streaming shows how a client uses Range to resume a download.
Falling Back to index.html for App Routes
A single-page app handles paths such as /books/42 in the browser, so the server must answer every path that is not an asset with index.html. We add a route that matches any GET path and serves that one file:
val indexHtml: Handler[Any, Throwable, Request, Response] =
Handler.fromFile(new File(siteDir, "index.html"))
val pages: Routes[Any, Response] =
Routes(
Method.GET / trailing -> indexHtml.contramap[(Path, Request)](_._2),
).sandbox
val site: Routes[Any, Response] = pages @@ assets
A route that ends in trailing passes the rest of the path to its handler along with the request, while the handler from Handler.fromFile takes only the request. Handler#contramap adapts it by dropping the path. Routes#sandbox turns the handler's failures into responses, so a missing index.html gives 404 Not Found instead of a failed route.
The route under /assets begins with a literal segment, so it wins over trailing for those paths. A missing asset still gets 404 Not Found and never an HTML page, which would only confuse the browser:
$ curl -i localhost:8080/books/42
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06abe-e7"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/html; charset=utf-8
date: Wed, 02 Dec 2026 16:52:06 GMT
content-length: 231
<!DOCTYPE html>
...
$ curl -i localhost:8080/assets/missing.js
HTTP/1.1 404 Not Found
date: Wed, 02 Dec 2026 16:52:06 GMT
content-length: 0
Every other path gets index.html, /favicon.ico and /robots.txt included. Put such files under /assets and link to them from the page, or give each one its own route.
Runnable version, with the site directory and assets middleware of the previous section: Step4SinglePageAppExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
// Run from the zio-http-example folder: scala-cli run src/main/scala/example/staticcaching/Step4SinglePageAppExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.staticcaching.Step4SinglePageAppExample"
package example.staticcaching
import java.io.File
import zio._
import zio.http._
/**
* Serve Static Files with Caching Headers — Falling Back to index.html
*
* Serves `site/assets` under `/assets` and answers every other `GET` path with
* `site/index.html`, so a single-page app can handle the path in the browser.
*/
object Step4SinglePageAppExample extends ZIOAppDefault {
// Setup from the previous section: the site directory and the assets middleware
val siteDir = new File("site")
val assets: Middleware[Any] =
Middleware.serveDirectory(Path.empty / "assets", new File(siteDir, "assets"))
val indexHtml: Handler[Any, Throwable, Request, Response] =
Handler.fromFile(new File(siteDir, "index.html"))
val pages: Routes[Any, Response] =
Routes(
Method.GET / trailing -> indexHtml.contramap[(Path, Request)](_._2),
).sandbox
val site: Routes[Any, Response] = pages @@ assets
def run = Server.serve(site).provide(Server.default)
}
Setting Cache-Control by Path
The two kinds of files need opposite policies. A hashed asset never changes under its name, because a new build gives new content a new name, so the browser may keep it for a year without asking. index.html keeps its name across builds and points to the current asset names, so the browser must check it on every use:
| Path | Cache-Control | Meaning |
|---|---|---|
/assets/* | public, max-age=31536000, immutable | Any cache may store it for a year and reuse it unchecked. |
| other paths | no-cache | The browser may store it but must revalidate on every use. |
Middleware.intercept builds a handler aspect from a function of the request and the response. We add the header to successful responses only, because a 404 sent with a one-year lifetime would be stored like a file:
val oneYear: Header.CacheControl =
Header.CacheControl.Multiple(
NonEmptyChunk(
Header.CacheControl.Public,
Header.CacheControl.MaxAge(365 * 24 * 60 * 60),
Header.CacheControl.Immutable,
),
)
val cacheHeaders: HandlerAspect[Any, Unit] =
Middleware.intercept { (request, response) =>
if (!response.status.isSuccess) response
else if (request.path.startsWith(Path.root / "assets")) response.addHeader(oneYear)
else response.addHeader(Header.CacheControl.NoCache)
}
Applied with site @@ cacheHeaders, the aspect sends each policy with its files:
$ curl -i localhost:8080/assets/app.3f9a1c.js
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06ac2-54"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/javascript; charset=utf-8
cache-control: public,max-age=31536000,immutable
date: Wed, 02 Dec 2026 16:52:27 GMT
content-length: 84
$ curl -i localhost:8080/books/42
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06abe-e7"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/html; charset=utf-8
cache-control: no-cache
date: Wed, 02 Dec 2026 16:52:27 GMT
content-length: 231
Send immutable and a long max-age only for files whose names change with their content. A file such as /assets/logo.svg that is replaced under the same name would stay old in browsers for up to a year.
Runnable version, with the setup of the two previous sections: Step5CacheControlExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
// Run from the zio-http-example folder: scala-cli run src/main/scala/example/staticcaching/Step5CacheControlExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.staticcaching.Step5CacheControlExample"
package example.staticcaching
import java.io.File
import zio._
import zio.http._
/**
* Serve Static Files with Caching Headers — Setting Cache-Control by Path
*
* Adds a `Cache-Control` header to every successful response: assets under
* `/assets` may be cached for a year, while `index.html` must be revalidated on
* each use.
*/
object Step5CacheControlExample extends ZIOAppDefault {
// Setup from the two previous sections: the assets middleware and the index.html fallback
val siteDir = new File("site")
val assets: Middleware[Any] =
Middleware.serveDirectory(Path.empty / "assets", new File(siteDir, "assets"))
val indexHtml: Handler[Any, Throwable, Request, Response] =
Handler.fromFile(new File(siteDir, "index.html"))
val pages: Routes[Any, Response] =
Routes(
Method.GET / trailing -> indexHtml.contramap[(Path, Request)](_._2),
).sandbox
val site: Routes[Any, Response] = pages @@ assets
val oneYear: Header.CacheControl =
Header.CacheControl.Multiple(
NonEmptyChunk(
Header.CacheControl.Public,
Header.CacheControl.MaxAge(365 * 24 * 60 * 60),
Header.CacheControl.Immutable,
),
)
val cacheHeaders: HandlerAspect[Any, Unit] =
Middleware.intercept { (request, response) =>
if (!response.status.isSuccess) response
else if (request.path.startsWith(Path.root / "assets")) response.addHeader(oneYear)
else response.addHeader(Header.CacheControl.NoCache)
}
def run = Server.serve(site @@ cacheHeaders).provide(Server.default)
}
Answering Conditional Requests with 304
With no-cache, the browser asks for index.html on every page load and sends the stored ETag in If-None-Match. When the tag still matches the file, the server should answer 304 Not Modified with no body, and the browser uses its stored copy.
Header.IfNoneMatch is either Any (the value *) or ETags, a list of tags kept as they appear in the header, quotes and W/ prefix included. If-None-Match uses weak comparison (RFC 9110, section 13.1.2), where only the quoted part counts, so we parse each tag with Header.ETag.parse and compare that part:
def opaqueTag(etag: Header.ETag): String = etag match {
case Header.ETag.Strong(value) => value
case Header.ETag.Weak(value) => value
}
def matches(ifNoneMatch: Header.IfNoneMatch, etag: Header.ETag): Boolean =
ifNoneMatch match {
case Header.IfNoneMatch.Any => true
case Header.IfNoneMatch.ETags(tags) =>
tags.exists(tag => Header.ETag.parse(tag).map(opaqueTag) == Right(opaqueTag(etag)))
}
The aspect replaces a matching GET response with a 304 that keeps the response's headers, ETag and Cache-Control included, and drops the body. It checks 206 Partial Content responses too, because the server evaluates If-None-Match before Range (RFC 9110, section 13.2.2); for those, it removes the Content-Range header:
val conditionalGet: HandlerAspect[Any, Unit] =
Middleware.intercept { (request, response) =>
val servedFile = response.status == Status.Ok || response.status == Status.PartialContent
val notModified =
request.method == Method.GET && servedFile &&
request.header(Header.IfNoneMatch).zip(response.header(Header.ETag)).exists { case (inm, etag) =>
matches(inm, etag)
}
if (notModified)
Response(status = Status.NotModified, headers = response.headers).removeHeader(Header.ContentRange)
else response
}
The body of a file response holds the file but does not read it until the response is written, so a 304 never reads the file's content. The aspect answers If-None-Match only, not If-Modified-Since: a browser sends If-None-Match whenever the stored response carries an ETag, which Handler.fromFile always sets, and RFC 9110 says a server ignores If-Modified-Since when If-None-Match is present.
The order of the aspects matters. The aspect applied last sees the response last, so conditionalGet goes after cacheHeaders:
request ──► conditionalGet ──► cacheHeaders ──► site (index.html, /assets)
response ◄── 304 or as is ◄── Cache-Control ◄── file with ETag
We serve the site with both aspects:
Server.serve(site @@ cacheHeaders @@ conditionalGet).provide(Server.default)
In the other order, cacheHeaders sees the 304, which is not a success status, and the reply has no Cache-Control. With this order, a request that sends the current tag gets the 304 with both headers, and a request with an old tag gets the file:
$ curl -i -H 'If-None-Match: W/"1a237a06abe-e7"' localhost:8080/books/42
HTTP/1.1 304 Not Modified
accept-ranges: bytes
etag: W/"1a237a06abe-e7"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/html; charset=utf-8
cache-control: no-cache
date: Wed, 02 Dec 2026 16:53:06 GMT
content-length: 0
$ curl -i -H 'If-None-Match: W/"1a237a06abe-e6"' localhost:8080/books/42
HTTP/1.1 200 OK
accept-ranges: bytes
etag: W/"1a237a06abe-e7"
last-modified: Wed, 02 Dec 2026 16:39:49 GMT
content-type: text/html; charset=utf-8
cache-control: no-cache
date: Wed, 02 Dec 2026 16:53:06 GMT
content-length: 231
Putting It Together
The complete server joins the sections: the /assets middleware, the index.html fallback, the Cache-Control aspect and the 304 aspect, in that order. It has no code that the sections do not show:
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
// Run from the zio-http-example folder: scala-cli run src/main/scala/example/staticcaching/CompleteExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.staticcaching.CompleteExample"
package example.staticcaching
import java.io.File
import zio._
import zio.http._
/**
* Serve Static Files with Caching Headers — the complete server
*
* Serves a single-page app from the `site` directory, sets `Cache-Control` by
* path, and answers `If-None-Match` requests with 304 Not Modified when the
* file's `ETag` still matches.
*/
object CompleteExample extends ZIOAppDefault {
val siteDir = new File("site")
val assets: Middleware[Any] =
Middleware.serveDirectory(Path.empty / "assets", new File(siteDir, "assets"))
val indexHtml: Handler[Any, Throwable, Request, Response] =
Handler.fromFile(new File(siteDir, "index.html"))
val pages: Routes[Any, Response] =
Routes(
Method.GET / trailing -> indexHtml.contramap[(Path, Request)](_._2),
).sandbox
val site: Routes[Any, Response] = pages @@ assets
val oneYear: Header.CacheControl =
Header.CacheControl.Multiple(
NonEmptyChunk(
Header.CacheControl.Public,
Header.CacheControl.MaxAge(365 * 24 * 60 * 60),
Header.CacheControl.Immutable,
),
)
val cacheHeaders: HandlerAspect[Any, Unit] =
Middleware.intercept { (request, response) =>
if (!response.status.isSuccess) response
else if (request.path.startsWith(Path.root / "assets")) response.addHeader(oneYear)
else response.addHeader(Header.CacheControl.NoCache)
}
def opaqueTag(etag: Header.ETag): String = etag match {
case Header.ETag.Strong(value) => value
case Header.ETag.Weak(value) => value
}
def matches(ifNoneMatch: Header.IfNoneMatch, etag: Header.ETag): Boolean =
ifNoneMatch match {
case Header.IfNoneMatch.Any => true
case Header.IfNoneMatch.ETags(tags) =>
tags.exists(tag => Header.ETag.parse(tag).map(opaqueTag) == Right(opaqueTag(etag)))
}
val conditionalGet: HandlerAspect[Any, Unit] =
Middleware.intercept { (request, response) =>
val servedFile = response.status == Status.Ok || response.status == Status.PartialContent
val notModified =
request.method == Method.GET && servedFile &&
request.header(Header.IfNoneMatch).zip(response.header(Header.ETag)).exists { case (inm, etag) =>
matches(inm, etag)
}
if (notModified)
Response(status = Status.NotModified, headers = response.headers).removeHeader(Header.ContentRange)
else response
}
def run = Server.serve(site @@ cacheHeaders @@ conditionalGet).provide(Server.default)
}
Run it from the zio-http-example folder, which holds the site directory, and open http://localhost:8080/books/42 in a browser: the page's script finds the path in the browser and shows Showing /books/42.
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/staticcaching/, and the site it serves is in zio-http-example/site/. The examples find site in the working directory, so run them from the zio-http-example folder with scala-cli run src/main/scala/example/staticcaching/<File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.staticcaching.<ObjectName>", which runs them in zio-http-example. Each example starts a server on port 8080; send it the curl requests above.
Going Further
- Middleware lists
Middleware.serveDirectoryandMiddleware.serveResources. - Handler shows
Handler.fromFile, which serves a single file from any route. - HandlerAspect covers the other ways to intercept requests and responses.
- Server shows how to compress responses, which helps text assets such as JavaScript and CSS.
- How to Package and Deploy a ZIO HTTP Server covers shipping the server, and the
sitedirectory with it.