
# Static resources

Files in `lib/resources/static/` (or `lib/resources/public/`) are served as they are: `lib/resources/static/app.css` answers `GET /app.css`, and `lib/resources/static/index.html` is the welcome page at `/`. Other folders, a Flutter web build among them, are served from `file:` locations.

## Why

Most web applications have files that no code needs to touch: a front end, images, fonts, a `robots.txt`. Spring Boot serves `src/main/resources/static/` without any code, and so does this starter. One process then serves the API and the site, with one origin and no CORS. The starter also does what a good static file server does:

- the right `Content-Type`, never guessed from the content;
- `ETag` and `Last-Modified`, with `304 Not Modified` for a browser that has the file;
- `Cache-Control` from the configuration;
- byte ranges and `HEAD`;
- precompressed `.br` and `.gz` files;
- deep links of a single-page app (`/books/42` gets `index.html`);
- strict path checks, so no request reads a file outside its location.

## Example

A Flutter web app with its API, in one server:

```text
my_app/
  build/web/                 # flutter build web
    index.html
    main.dart.js
    flutter_bootstrap.js
    assets/...
  lib/resources/
    application.yaml
    static/robots.txt        # embedded in the executable
```

```yaml
# lib/resources/application.yaml
spring:
  web:
    resources:
      static-locations: file:build/web/, resources:static/
      spa-fallback: true      # /books/42 opened in the browser gets index.html
      directory-index: true   # /guide gets guide/index.html
      cache:
        cachecontrol:
          no-cache: true      # always revalidate: a 304 when nothing changed
      chain:
        compressed: true      # main.dart.js.br / .gz when the browser takes them
  mvc:
    static-path-pattern: /**  # the default
server:
  mime-mappings:
    wasm: application/wasm
```

```dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

// The API keeps its paths: controllers are asked before the files.
@RestController()
@RequestMapping('/api')
class BookController {
  @GetMapping('/books')
  List<String> books() => ['Dune', 'Foundation'];
}

// More mappings with their own caching.
@Configuration()
class WebConfig with WebMvcConfigurer {
  @override
  void addResourceHandlers(ResourceHandlerRegistry registry) {
    // Fingerprinted files never change: kept by browsers for a year.
    registry
        .addResourceHandler(['/static-assets/**'])
        .addResourceLocations(['file:build/web/static-assets/'])
        .setCacheControl(
          CacheControl.maxAge(const Duration(days: 365)).cachePublic().immutable(),
        );
  }
}
```

## Where files come from

A location is one of:

| Prefix | Meaning | Example |
|---|---|---|
| `resources:` | A folder of `lib/resources/`. The generator embeds these files in the executable. In tests and with `dart run`, the folder on disk and test resource directories are looked in too. | `resources:static/` |
| `file:` | A directory read at run time, relative to the working directory or absolute. | `file:build/web/`, `file:/srv/shop/web/` |

- A missing trailing `/` is added.
- The first location that has the file serves it.
- A location that does not exist finds nothing and fails nothing. A directory created after the start is found then.
- Another prefix (`classpath:`, `https:`) **stops the start**. So does `resources:` alone: it would serve the configuration files of `lib/resources/`.
- The generator embeds files of up to 1 MB. Put large files, and a whole Flutter build, in a `file:` location: an AOT executable then ships with the folder next to it.

## What a request gets

- **Controllers win.** The static resources are asked after every controller (their handler mapping has the order `Ordered.lowestPrecedence - 1`), so a mapping always keeps its path.
- **Filters run first**, as for any request, the security filter chain among them. `HandlerInterceptor`s do not run: they are for controller methods.
- **The most specific pattern** of the mappings serves a request: `/static-assets/**` before `/**`.
- **Only `GET` and `HEAD` read a file.** `OPTIONS` gets `200` with `Allow: GET,HEAD,OPTIONS`, a CORS pre-flight is answered from the CORS rules, and other methods get `405`.
- **A path without a file** goes on to the next handler mapping, and ends as the dispatcher's `404`. There is never a directory listing.
- **The context path** (`server.context-path`) is in front of every file path, as of every mapping.

The answer to a file:

| Header | Value |
|---|---|
| `Content-Type` | From the extension: `server.mime-mappings`, then the built-in types (see [Downloads](streaming/downloads.md)), `application/json` for `apple-app-site-association`, else `application/octet-stream`. Never guessed from the content. |
| `X-Content-Type-Options` | `nosniff`, so browsers do not guess either. |
| `ETag` | A weak tag: the length and modification time of a file, the length and a hash of an embedded file. |
| `Last-Modified` | The modification time of a file (not of an embedded one), unless `cache.use-last-modified=false`. |
| `Cache-Control` | From `cache.period` or `cache.cachecontrol.*`; none by default. Sent with a `304` too. |
| `Accept-Ranges` | `bytes`. |
| `Content-Encoding`, `Vary` | For a precompressed variant (`chain.compressed`). |

- **`304 Not Modified`** for `If-None-Match` with the `ETag` (compared weakly), or, without `If-None-Match`, for `If-Modified-Since` at or after `Last-Modified`. `If-Unmodified-Since` before `Last-Modified` is a `412`.
- **One `Range`** is a `206`; past the end, a `416`. `If-Range` with a date applies the range only to that version. The `ETag` is weak, so an `If-Range` with a tag never matches and the whole file is sent. Rules in [Downloads](streaming/downloads.md).
- **Large files are streamed** from disk, never read whole.

## The welcome page

`GET /` from a client that takes HTML gets the `index.html` that `/index.html` would get.

- Only with `spring.mvc.static-path-pattern=/**` (the default) and `spring.web.resources.add-mappings=true`.
- "Takes HTML": an `Accept` that includes `text/html` with a quality above 0, `*/*` included. No `Accept` header counts as `*/*`.
- Other folders get their `index.html` only with `directory-index`.

## Folder pages: `directory-index`

With `spring.web.resources.directory-index=true`, a path with no file whose folder holds an `index.html` gets that file: `/guide` and `/guide/` are both answered with `guide/index.html`, as static hosts (Cloudflare Pages, Netlify) answer.

- The `index.html` is looked up as any other file: inside the location, with the same checks on every segment.
- It is tried before the single-page fallback.
- Use it for pages pre-rendered per path, such as the pages the Flutter starter writes for search engines (`spring.flutter.web.seo.*`), or a documentation site.

## Single-page apps: `spa-fallback`

A single-page app (a Flutter web build, a JavaScript router) has one `index.html` and routes in the browser. When the user opens `/books/42` directly, or reloads the page there, the server has no such file. With `spring.web.resources.spa-fallback=true`, such a request gets `index.html`, and the app's router opens the page.

The fallback applies only when all of these hold:

- the method is `GET` or `HEAD`;
- no controller and no file answers the path;
- the last segment has no extension (`/books/42`, not `/books/42.json` or `/main.dart.js`);
- the path is not under `.well-known/` (deep-link verification must see a `404`, not HTML);
- the `Accept` header names `text/html` with a quality above 0. A browser's navigation does; a script's `fetch` of a missing API path, which sends `*/*`, does not.

Everything else keeps its `404`: a missing script, a missing image, an unknown API path called by code.

The `index.html` served is the one `/index.html` gets, so the fallback needs a mapping that covers `/index.html` (the default `/**` does).

## Precompressed files: `chain.compressed`

With `spring.web.resources.chain.compressed=true`, a file `app.js.br` or `app.js.gz` next to `app.js` is sent instead of `app.js` to a client whose `Accept-Encoding` takes it.

- Brotli (`.br`) is tried first, then gzip (`.gz`). A coding with `q=0` is not taken.
- The answer has `Content-Encoding: br` or `gzip`, the `Content-Type` of the original file, and the variant's own `ETag`.
- `Vary: Accept-Encoding` is added whenever a variant exists, also when the client takes none, so caches keep the versions apart.
- `server.compression` does not compress it again.
- Make the variants at build time (`brotli -k`, `gzip -k`). Highest compression levels cost nothing at run time.

`server.compression.enabled=true` gzips other files of a compressible type on the fly. See [Compression](server/compression.md).

## Path security

A request never reads outside its location. The path is decoded once and checked before any file is looked up. These are refused, and the request is a `404` (some are already a `400` from the server):

- `.` and `..` segments, encoded or doubly encoded separators and dots (`%2e%2e`, `%252e`), backslashes;
- an empty segment (`a//b`) and a `;` anywhere in the path (`..;x`, matrix parameters);
- invalid UTF-8 (overlong forms, lone surrogates), control characters, spaces and other characters a request target never carries raw;
- Windows' device names (`CON`, `NUL`, `COM1`, ...), short names (`PROGRA~1`), alternate data streams (`:`), wildcards, trailing dots and spaces;
- characters that look like dots and slashes (fullwidth and other confusable forms);
- `WEB-INF` and `META-INF`, in any case, as in Spring;
- hidden files: a segment that starts with a dot (`.env`, `.git/`), except `.well-known` as the first segment, so `/.well-known/assetlinks.json` and `/.well-known/apple-app-site-association` work.

The file found is resolved with its symbolic links, and refused when it leaves the location, when a segment of its real path is not allowed, or when it is not a regular file (a directory, a pipe, a device).

## Properties

### `spring.web.resources.static-locations`

| Type | Default |
|---|---|
| `List<String>` | `resources:static/, resources:public/` |

Where the files of the default mapping come from, in order; the first location with the file wins. A comma list or a YAML list. Change it to serve a Flutter build (`file:build/web/`) or a directory on the server (`file:/srv/shop/web/`). Setting it replaces the defaults: list `resources:static/` again if you still want it.

```yaml
spring:
  web:
    resources:
      static-locations:
        - file:build/web/
        - resources:static/
```

Spring Boot's defaults also hold `classpath:/META-INF/resources/` and `classpath:/resources/`; Dart has no jars, so they are left out, and `classpath:` is written `resources:`.

### `spring.mvc.static-path-pattern`

| Type | Default |
|---|---|
| `String` | `/**` |

The path pattern the default mapping serves its files under. `/**` serves `static/app.css` as `/app.css`; `/assets/**` serves it as `/assets/app.css`. Change it to keep the files under a prefix, out of the way of other paths. With any other pattern than `/**`, there is no welcome page, and the single-page fallback finds no `/index.html` unless another mapping covers it.

```yaml
spring:
  mvc:
    static-path-pattern: /assets/**
```

### `spring.web.resources.add-mappings`

| Type | Default |
|---|---|
| `bool` | `true` |

`false` turns off the default mapping (`static-locations` under `static-path-pattern`) and the welcome page. The mappings a `WebMvcConfigurer` adds stay. Use it for an API that serves no files, or when your own mappings should be the only ones.

```yaml
spring:
  web:
    resources:
      add-mappings: false
```

### `spring.web.resources.spa-fallback`

| Type | Default |
|---|---|
| `bool` | `false` |

Serves `index.html` for a browser's navigation to a path that is no file and no handler, as described under "Single-page apps" above. Turn it on for a Flutter web app with path URLs (`usePathUrlStrategy`) or any client-side router. This key is this starter's own; Spring Boot has no such property.

### `spring.web.resources.directory-index`

| Type | Default |
|---|---|
| `bool` | `false` |

Serves the `index.html` of a folder for the folder's path, as described under "Folder pages" above. Off by default, as in Spring Boot, whose welcome page covers `/` only. This key is this starter's own.

### `spring.web.resources.chain.compressed`

| Type | Default |
|---|---|
| `bool` | `false` |

Serves precompressed `.br` and `.gz` variants, as described under "Precompressed files" above. Turn it on when your build writes them.

### `spring.web.resources.cache.period`

| Type | Default |
|---|---|
| `Duration` | none |

`Cache-Control: max-age=<seconds>` for every file of the default mapping: how long browsers may use a file without asking. A plain number is seconds (`3600`); a unit works too (`1h`, `7d`). `0` sends `Cache-Control: no-store`. Not set: no `Cache-Control` header, and browsers use their own heuristics. Any `cache.cachecontrol.*` key replaces it.

```yaml
spring:
  web:
    resources:
      cache:
        period: 1h
```

### `spring.web.resources.cache.use-last-modified`

| Type | Default |
|---|---|
| `bool` | `true` |

Whether a file's modification time is sent as `Last-Modified` and checked against `If-Modified-Since`. Turn it off when the modification times mean nothing (files copied at deploy time with new dates on every server behind a load balancer); the `ETag` still gives `304`s. Embedded files have no modification time either way.

### `spring.web.resources.cache.cachecontrol.*`

The `Cache-Control` header, directive by directive. When any of these keys is set, they replace `cache.period`. The header is built as Spring Boot builds it: `no-store` first if set, else `no-cache` if set, else `max-age` if set; then the other directives.

| Key | Type | Default | Directive and meaning |
|---|---|---|---|
| `spring.web.resources.cache.cachecontrol.max-age` | `Duration` | none | `max-age=<seconds>`: how long the answer may be reused without asking. A plain number is seconds. Ignored when `no-store` or `no-cache` is set. |
| `spring.web.resources.cache.cachecontrol.no-cache` | `bool` | none | `no-cache`: may be stored, but reused only after the server confirmed it (a cheap `304` with the `ETag`). Wins over `max-age`. |
| `spring.web.resources.cache.cachecontrol.no-store` | `bool` | none | `no-store`: never stored. Wins over `no-cache` and `max-age`. |
| `spring.web.resources.cache.cachecontrol.must-revalidate` | `bool` | none | `must-revalidate`: once stale, not used without asking the server, even offline. |
| `spring.web.resources.cache.cachecontrol.no-transform` | `bool` | none | `no-transform`: proxies must not change the content (recompress images, for one). |
| `spring.web.resources.cache.cachecontrol.cache-public` | `bool` | none | `public`: shared caches (CDNs, proxies) may store it too. |
| `spring.web.resources.cache.cachecontrol.cache-private` | `bool` | none | `private`: only the user's own browser may store it. |
| `spring.web.resources.cache.cachecontrol.proxy-revalidate` | `bool` | none | `proxy-revalidate`: `must-revalidate` for shared caches only. |
| `spring.web.resources.cache.cachecontrol.s-max-age` | `Duration` | none | `s-maxage=<seconds>`: how long shared caches may keep it; overrides `max-age` for them. |
| `spring.web.resources.cache.cachecontrol.stale-while-revalidate` | `Duration` | none | `stale-while-revalidate=<seconds>`: how long a stale answer may be used while a fresh one is fetched in the background. |
| `spring.web.resources.cache.cachecontrol.stale-if-error` | `Duration` | none | `stale-if-error=<seconds>`: how long a stale answer may be used when the server fails. |

```yaml
# max-age=60, must-revalidate, no-transform, public, proxy-revalidate,
# s-maxage=30, stale-if-error=5, stale-while-revalidate=10
spring:
  web:
    resources:
      cache:
        cachecontrol:
          max-age: 60
          must-revalidate: true
          no-transform: true
          cache-public: true
          proxy-revalidate: true
          s-max-age: 30
          stale-if-error: 5
          stale-while-revalidate: 10
```

Which to choose:

- **Files whose names change with their content** (fingerprinted: `app.3f9a.js`): `max-age` of a year, `public`, and `immutable` through a `WebMvcConfigurer` mapping (there is no property for `immutable`).
- **Files whose names stay the same** (`index.html`, a Flutter build's `main.dart.js`): `no-cache`. The browser asks each time, and gets a `304` without a body while nothing changed, so a new deploy is seen at once.
- **Private files** should not be static resources at all: serve them from a controller that checks access.

The same keys drive the headers of a Flutter web build on a static host: in a Flutter app's configuration, the generator writes them into `web/_headers` for Cloudflare Pages and Netlify. There the value goes to the app's assets (`/assets/*`) only, and the files without a hash get `no-cache`. See [The browser cache of a web build](../spring-boot-starter-flutter/cache-headers.md).

### `server.mime-mappings.*`

| Type | Default |
|---|---|
| `Map<String, String>` | empty |

More media types by file extension, on top of the built-in ones; an extension listed here wins. The extension is matched in any case, with or without a leading dot. Add the types your files need that the built-in table lacks.

```yaml
server:
  mime-mappings:
    wasm: application/wasm
    glb: model/gltf-binary
    epub: application/epub+zip
```

## More mappings: `addResourceHandlers`

A `WebMvcConfigurer` bean adds mappings with their own patterns, locations and caching. A mapping with the same pattern as `spring.mvc.static-path-pattern` replaces the default one.

| `ResourceHandlerRegistry` | Meaning |
|---|---|
| `addResourceHandler(List<String> pathPatterns)` | Adds a mapping for the patterns and returns its registration. |
| `hasMappingForPattern(String pattern)` | Whether a registration maps exactly this pattern. |
| `registrations` | The registrations in the order they were added. |

| `ResourceHandlerRegistration` | Default | Meaning |
|---|---|---|
| `addResourceLocations(List<String> locations)` | none | Adds `resources:` or `file:` locations, after those already added. |
| `setCachePeriod(int? seconds)` | `null` | `Cache-Control: max-age=<seconds>`; `0` sends `no-store`; `null` none. |
| `setCacheControl(CacheControl? cacheControl)` | `null` | The whole `Cache-Control`; wins over `setCachePeriod`. |
| `setUseLastModified(bool use)` | `true` | Whether `Last-Modified` is sent and checked. |
| `setCompressed(bool compressed)` | `false` | Whether precompressed `.br` and `.gz` variants are served. |

Every method returns the registration, so calls chain. The default mapping gets the `spring.web.resources.*` settings; a mapping you add gets only what you set on it.

```dart
@Configuration()
class DocsConfig with WebMvcConfigurer {
  @override
  void addResourceHandlers(ResourceHandlerRegistry registry) {
    // The handbook under /docs/, from its own folder, revalidated.
    registry
        .addResourceHandler(['/docs/**'])
        .addResourceLocations(['file:/srv/handbook/'])
        .setCacheControl(CacheControl.noCache())
        .setCompressed(true);
  }
}
```

To serve a file of a location from your own code (a controller or a filter), create a `ResourceHttpRequestHandler(locations: [...])`: `getResource(path)` finds the file after the same checks, and `handleResource(found, request, response, writer)` answers with it, the `ResponseWriter` bean as `writer`.

## CORS

The global CORS rules apply to the files: the `addCorsMappings` of a `WebMvcConfigurer`, or the `CorsConfigurationSource` bean named `corsConfigurationSource`. `@CrossOrigin` does not, as it belongs to controllers. See [CORS](cors.md).

## In Spring (Java)

```properties
spring.web.resources.static-locations=classpath:/static/,file:build/web/
spring.web.resources.cache.cachecontrol.max-age=1h
```

Differences that matter:

- Locations are `resources:` and `file:`, not `classpath:`. Another prefix stops the start.
- `spa-fallback` and `directory-index` are this starter's own keys.
- Precompressed files are `chain.compressed` (a property) or `setCompressed` (a mapping). Spring uses `resourceChain(true).addResolver(new EncodedResourceResolver())`. `spring.web.resources.chain.enabled`, `chain.cache`, the version strategies and the webjars mapping are not supported.
- The checks are stricter: dot files are not served (`.well-known/` is), `;` and empty segments are a `404`, a symbolic link that leaves the location is refused, and so is a path that only Windows would read as another file.
- Files get a weak `ETag` (Spring sends none unless an `etagGenerator` is set), `X-Content-Type-Options: nosniff` (Spring Security adds it in Spring), and `Cache-Control` on a `304` too.
- A path without a file is the dispatcher's `404` (`No endpoint GET /x.`). Spring 6.1 answers `No static resource x.`.

## See also

- [Downloads](streaming/downloads.md): files from controllers
- [WebMvcConfigurer](web-mvc-configurer.md)
- [Compression](server/compression.md)
- [Filters](filters.md)
- [CORS](cors.md)
- [The browser cache of a Flutter web build](../spring-boot-starter-flutter/cache-headers.md)
- [All properties](properties.md)
