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:

Example

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

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
# 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
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/

What a request gets

The answer to a file:

Header Value
Content-Type From the extension: server.mime-mappings, then the built-in types (see Downloads), 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).

The welcome page

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

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.

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:

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.

server.compression.enabled=true gzips other files of a compressible type on the fly. See Compression.

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):

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.

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.

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.

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.

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 304s. 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.
# 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:

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.

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.

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.

@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.

In Spring (Java)

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

Differences that matter:

See also