
# The embedded server

`spring_boot_starter_web` runs an HTTP server inside the application. It starts when the context is ready and stops when the context closes. You configure it with `server.*` properties.

## Why

You do not write `HttpServer.bind` or a request loop. The starter does it for you, in the same way as Spring Boot runs Tomcat for you:

- the `webServerFactory` bean creates the server from the `server.*` properties;
- the `webServerStartStopLifecycle` bean starts it after the beans are ready and stops it at shutdown;
- every request goes to the `dispatcherHandler` bean, which runs the filters and the controllers.

The default server is `dart:io`'s `HttpServer`. It runs on the Dart VM, in a compiled executable, and in a Flutter app on Android, iOS, macOS, Windows and Linux. It speaks HTTP/1.1 (with TLS if you want). It does not speak HTTP/2.

## Example

```yaml
# lib/resources/application.yml
server:
  port: 8080
  address: 0.0.0.0
  context-path: /shop
  max-http-request-body-size: 20MB
  mime-mappings:
    wasm: application/wasm
spring:
  main:
    register-shutdown-hook: true   # Ctrl+C and SIGTERM stop the server gracefully
  mvc:
    log-request-details: false
```

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

import 'spring_gen/main.spring.dart';

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
```

```bash
dart run build_runner build
dart run bin/main.dart
# INFO  Web server started on port 8080 (http)
```

With this configuration, `@GetMapping('/books')` answers `GET http://host:8080/shop/books`.

## Properties

| Key | Type | Default | Meaning |
|---|---|---|---|
| `server.port` | `int` | `8080` | The port to listen on. `0` picks a free port. |
| `server.address` | `String` | all interfaces; `127.0.0.1` in Flutter apps | The address to listen on: an IP address or a host name. |
| `server.context-path` | `String` | none | A prefix of every path, such as `/shop`. |
| `server.max-http-request-body-size` | `DataSize` | `10MB` | The largest request body. Larger is a 413. `-1`: no limit. |
| `server.mime-mappings.<ext>` | `Map<String, String>` | empty | More media types for static files, by file extension. |
| `spring.main.web-application-type` | `String` | not set | `none` starts no server. |
| `spring.test.web-environment` | `String` | not set | Set by tests: which test environments start a server. |
| `spring.mvc.log-request-details` | `bool` | `false` | Show parameter and header values in the request logs. |
| `local.server.port` | `int` | written by the server | The port the server really listens on. Read it; do not set it. |

The other `server.*` keys have their own pages: [TLS](ssl.md), [compression](compression.md), [timeouts](timeouts.md), [overload](overload.md), [the pool of isolates](isolates.md) and [its scaling](scaling.md), [reverse proxy](reverse-proxy.md), [shutdown](shutdown.md), [WebSocket](websocket.md) and [sessions](../sessions.md). The full list is on [All properties](../properties.md).

### `server.port`

- **Type:** `int`. **Default:** `8080`.
- **What it does:** the TCP port the server listens on.
- **`0`:** the system picks a free port. The real port is known only once the server listens. Read it from `local.server.port`, from a `WebServerInitializedEvent`, or from `WebServer.port`.
- **Why change it:** another program uses `8080`; a platform gives you a port (a `PORT` variable); several instances run on one machine; tests need a free port.
- **Example:** `server.port=9090`, or `--server.port=9090` on the command line, or `SERVER_PORT=9090` in the environment.
- **Wrong value:** `server.port=abc` stops the start with a binding failure that names `server.port`.
- **Port in use:** the start fails. No `ApplicationStartedEvent`, no runners, no `ApplicationReadyEvent`. The `ApplicationFailedEvent` is published, the context closes, and the program ends with a non-zero exit code. The report:

```text
Web server failed to start. Port 8080 was already in use.

Action: Identify and stop the process that is listening on port 8080, or
configure this application to listen on another port (server.port; 0 picks a free one).
```

The port is in use also when the same process already listens on it.

A port computed in code goes through a `WebServerFactoryCustomizer` (see "Changing the server in code" below).

### `local.server.port`

- **Type:** `int`. **Set by:** the server, once it listens.
- **What it is:** the port the server really got. With `server.port=0` it is the only way to know the port from configuration.
- **Where it lives:** a property source named `server.ports`, put first in the environment.
- **Why you read it:** to log a URL, to register the service with a discovery server, or to call the server in a test.

```dart
@Component()
@Log()
class StartupUrl {
  @EventListener()
  void onServer(WebServerInitializedEvent event) =>
      log.info('Open http://localhost:${event.port}/');
}
```

Setting `local.server.port` yourself does nothing: nothing reads it to choose the port.

### `server.address`

- **Type:** `String`. **Default:** not set, which listens on every interface (IPv4 and IPv6). **In a Flutter app the default is `127.0.0.1`.**
- **Values:** an IPv4 or IPv6 address (`0.0.0.0`, `127.0.0.1`, `::1`), `localhost` (read as `127.0.0.1`), or a host name, which is looked up when the server starts (the first address found is used).
- **Why change it:** listen on `127.0.0.1` only, so that the server is reachable from this machine only (a local tool, a server behind a proxy on the same host). Or, in a Flutter app, set `0.0.0.0` on purpose to open the server to the local network.
- **Example:** `server.address=127.0.0.1`.
- **Wrong value:** an address that cannot be bound, or a host name that cannot be looked up, fails the start with `WebServerException: cannot listen on <address>:<port>` and the socket error.

### `server.context-path`

- **Type:** `String`. **Default:** none.
- **What it does:** every request path must start with this prefix. The prefix is removed before routing. So `@GetMapping('/books')` answers `/shop/books`, and `/shop` alone is the path `/`.
- **Outside the prefix:** a request to `/books` (without `/shop`) gets a 404, as for a path that no handler takes.
- **Normalised:** a missing leading `/` is added and trailing `/` are removed. `shop/` becomes `/shop`.
- **Also affects:** the default `Path` of the session cookie (`server.session.cookie.path`), so the cookie goes only to the application's paths.
- **Why change it:** several applications share one host behind a proxy (`/shop`, `/admin`), and the proxy passes the full path.
- **Example:** `server.context-path=/shop`.
- **Note:** it is read by the dispatcher directly. A `WebServerFactoryCustomizer` that changes `contextPath` in the factory's settings does not change routing.

### `server.max-http-request-body-size`

- **Type:** `DataSize` (`512KB`, `10MB`, `1GB`; a plain number is bytes). **Default:** `10MB`. **`-1`:** no limit.
- **What it does:** a request body larger than this is answered with `413 Payload Too Large`, whatever its `Content-Type`. When `Content-Length` already says it is too large, the 413 comes before anything is read. A chunked body is counted while it is read.
- **Uploads:** the multipart resolver reads `multipart/form-data` with its own limit, `spring.web.multipart.max-request-size`, instead of this one. See [Uploads](../streaming/uploads.md).
- **One request:** a handler can set its own limit for the request it handles, before it reads the body, through the request attribute `maxRequestBodySizeAttribute`:

```dart
import 'dart:io' show File;

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

@RestController()
class ImageController {
  // Disk images up to 4 GB, written to a file as they arrive.
  @PutMapping('/images/{name}')
  @ResponseStatus(HttpStatus.noContent)
  Future<void> upload(ServerHttpRequest request, @PathVariable() String name) async {
    request.attributes[maxRequestBodySizeAttribute] = 4 << 30;
    await request.body.pipe(File('/srv/images/$name').openWrite());
  }
}
```

- **Why change it:** raise it for an API that takes big JSON documents; lower it to protect a small service from large bodies.
- **Not in Spring Boot:** Tomcat has no limit of this kind for every body. This is the starter's own key.

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

- **Type:** a map from file extension to media type. **Default:** empty (the built-in types apply).
- **What it does:** gives the `Content-Type` of static files by extension, on top of the built-in table. An extension listed here wins over the built-in type. The extension is matched in any case (`WASM` and `wasm` are the same).
- **Why change it:** a file type the built-in table does not know, or a type you want to send differently.
- **Example:**

```yaml
server:
  mime-mappings:
    wasm: application/wasm
    webmanifest: application/manifest+json
```

```properties
server.mime-mappings.wasm=application/wasm
server.mime-mappings.webmanifest=application/manifest+json
```

A file whose type is unknown is sent as `application/octet-stream`. See [Static resources](../static-resources.md).

### `spring.main.web-application-type`

- **Type:** `String`. **Default:** not set: a server starts.
- **`none`:** the web beans exist (the dispatcher, the controllers, `MockMvc` in tests), but no server starts. The value is compared without case.
- **Any other value:** the server starts. There is no `servlet` or `reactive` choice: there is one kind of server.
- **Why change it:** run a command-line task of the same application (a migration, a report) without opening a port. Or build for the browser, where no server can start.
- **Example:** `dart run bin/main.dart --spring.main.web-application-type=none`.

### `spring.test.web-environment`

- **Type:** `String`. **Default:** not set: a server starts.
- **Values:** `mock`, `random-port`, `defined-port`, `none`.
- **Who sets it:** the test support. `springBootTest(springApplication, webEnvironment: ...)` sets it (`mock` by default), and `ApplicationContextRunner` sets `mock`. You do not set it in `application.yml`.
- **What each value does:**

| Value | Server | Port |
|---|---|---|
| `mock` | none; `MockMvc` calls the dispatcher in memory | — |
| `random-port` | a real server | `0`, a free port, whatever `server.port` says |
| `defined-port` | a real server | `server.port` |
| `none` | none | — |

Any other value starts no server either. See [Testing](../testing.md).

### `spring.mvc.log-request-details`

- **Type:** `bool`. **Default:** `false`.
- **What it does:** the dispatcher logs every request at `debug` level, under the logger `spring.web.servlet.DispatcherServlet`. By default the values of query parameters and headers are shown as `masked`, because they may hold secrets. With `true` they are shown.
- **Always masked:** credentials stay `masked` even with `true`: the headers `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, and any header or parameter whose name contains `token`, `secret`, `key`, `password` or `session`.
- **Headers:** shown only at `trace` level.
- **Why change it:** debugging, on a developer machine. Leave it `false` in production.

```properties
logging.level.spring.web.servlet.DispatcherServlet=trace
spring.mvc.log-request-details=true
```

```text
DEBUG GET "/api/books", parameters={q=[dune], page=[2]}, headers={host: localhost:8080, authorization: masked}
DEBUG Completed 200 OK
```

Without `log-request-details`, the same request logs `parameters={masked}` and `headers={masked}`.

## The startup log line

When the server listens, the starter logs at `info` level, under the logger `spring.web.server`:

```text
Web server started on port 8080 (http)
```

The port is the real one (useful with `server.port=0`). The scheme is `https` when `server.ssl.certificate` is set and `server.ssl.enabled` is not `false`. When the server stops, it logs `Web server stopped`.

Other loggers of the starter:

| Logger | What |
|---|---|
| `spring.web.server` | start, stop, graceful shutdown, server errors, WebSocket sessions dropped |
| `spring.web.servlet.DispatcherServlet` | one line per request and its result (`debug`) |
| `spring.web.mvc` | the mappings found at startup (`debug`: their count; `trace`: each one), errors written |
| `spring.web.forwarded` | forwarded headers applied or ignored (`debug`) |
| `spring.web.session` | sessions |
| `spring.web.multipart` | uploads |

## The server's lifecycle

1. **The context starts.** The `webServerStartStopLifecycle` bean is a `SmartLifecycle` with phase `SmartLifecycle.defaultPhase - 2048`, as in Spring Boot. It starts before the lifecycle beans of the default phase and stops after them.
2. **Should a server run?** Not when `spring.main.web-application-type=none`. In a test, only for `random-port` and `defined-port`.
3. **The server is created.** The `webServerFactory` bean is asked for a server, with the `dispatcherHandler` as its handler.
4. **The socket is bound.** `dart:io` binds asynchronously. `SpringApplication` waits for it before it publishes `ApplicationStartedEvent`, runs the runners and publishes `ApplicationReadyEvent`. So when your `ApplicationRunner` runs, the server already listens.
5. **The port is published.** `local.server.port` is set, the startup line is logged, and a `WebServerInitializedEvent` is published.
6. **The context closes.** The server stops as `server.shutdown` says. See [Shutdown](shutdown.md).

To wait for the server in code (for example in a test without the test starter):

```dart
final lifecycle = context.getBean<WebServerStartStopLifecycle>();
final server = await lifecycle.started;          // null when no server runs
final uri = Uri.parse('http://localhost:${server!.port}/api/books');
```

A failure to start other than a port in use (an address that cannot be bound, a certificate that cannot be read) also fails the start. In a context started without `SpringApplication`, the failure is logged as `Web server failed to start` and the context closes.

### Stopping with `Ctrl+C`

`spring.main.register-shutdown-hook` is `false` by default here (Spring Boot: `true`), because listening for signals keeps a Dart program alive. Set it to `true` so that `Ctrl+C` (SIGINT) and SIGTERM close the context. Then the server stops gracefully and `@PreDestroy` methods run. Without it, the signal ends the process at once.

## What the server answers by itself

Some requests never reach your filters or controllers. The server answers them with a `ProblemDetail` (`application/problem+json`):

| Request | Answer |
|---|---|
| A method the starter does not know | `501 Not Implemented` |
| With `server.ssl.client-auth=need`, no client certificate | `403 Forbidden` |
| HTTP/1.1 without `Host`, a malformed `Host`, or an absolute target whose host is not the `Host` header | `400 Bad Request` |
| An encoded `/`, `\` or NUL in the path (`%2F`, `%5C`, `%00`) | `400` |
| A `.` or `..` segment hidden behind `;` (`/files/..;x/secret`) | `400` |
| A `%` escape that is not valid UTF-8 in the path or query (`/%FF`) | `400` |

Other rules of the `dart:io` server:

- **No `Server` header** and no `X-XSS-Protection`. `dart:io`'s `X-Frame-Options: SAMEORIGIN` and `X-Content-Type-Options: nosniff` are sent.
- **No default `Content-Type`.** An answer whose media type the application did not set has none.
- **1xx, 204, 304** get no `Content-Length` and no `Transfer-Encoding`; a 304 no `Content-Type`. A body written to them is dropped. A `HEAD` keeps the headers of the `GET`.
- **An unread body** (an upload answered with a 413 or 415): the answer goes out first, then up to 2 MB of the body are read and dropped, for at most 5 seconds, so the connection can serve the next request. A longer or slower body closes the connection.
- **An error after the response was committed:** the connection is dropped without finishing the response (no final chunk). The client sees a broken response, not a short one that looks complete.
- **A response header `dart:io` cannot send** (a non-ASCII character, a line break) fails before anything is sent: the header is dropped and the error is answered with a 500.
- **No connection limit** (Tomcat's `max-connections`). Put a proxy in front, or rely on the system's limit of open files.

Known limits of `dart:io` that matter behind a proxy:

- Two `Host` headers: the last one is used (Tomcat answers 400).
- A `%` without two hex digits is read as a plain `%` (`/a%G1` is `/a%25G1`).
- A raw `\` in the target becomes `/`, and `..` segments are then resolved: `/files/..\..\secret` arrives as `/secret`. A proxy whose rules look at paths must refuse `\` itself.
- A request with both `Content-Length` and `Transfer-Encoding` is answered 400, and its connection closes, when the server sees both headers. `dart:io` shows both only in some spellings (the length first and the encoding not written exactly `chunked`); in the others it drops the `Content-Length` and the request is read as chunked. Use a proxy that refuses such requests, to prevent request smuggling.

## Changing the server in code

Properties cover most needs. When a value is computed, declare a `WebServerFactoryCustomizer` bean. The starter calls each one once, on the default factory, after it applied `server.*`:

```dart
import 'dart:io' show Platform;

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

// The hosting platform gives the port in the PORT variable.
@Component()
class PortCustomizer implements WebServerFactoryCustomizer {
  @override
  void customize(ConfigurableWebServerFactory factory) =>
      factory.settings = factory.settings.copyWith(
        port: int.parse(Platform.environment['PORT'] ?? '8080'),
      );
}
```

`ServerProperties.copyWith` keeps a value when its argument is `null`, so it cannot reset `address`, `ssl` or a timeout to "none". `server.context-path` and `server.request-timeout` are read by the dispatcher from the properties, so a customizer cannot change them.

To replace the server entirely, declare your own `WebServerFactory` bean. The default one backs off (`@ConditionalOnMissingBean`):

```dart
@Configuration()
class ServerConfig {
  @Bean()
  WebServerFactory webServerFactory() => MyServerFactory(); // returns a WebServer
}
```

A `WebServer` has `start()`, `stop({Duration? timeout})` and `port`. Everything above the server works on `ServerHttpRequest` and `ServerHttpResponse` and never imports `dart:io`, so another server needs only these two classes. `IoWebServerFactory` and `IoWebServer` are in `package:spring_boot_starter_web/io.dart`, which you can import to wrap the default server or to start one outside the context:

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

Future<void> main() async {
  final server = IoWebServerFactory(const ServerProperties(port: 0)).getWebServer(
    FunctionHttpHandler((request, response) => response.send(200, 'pong')),
  );
  await server.start();
  print('listening on ${server.port}');
}
```

## Running in Flutter

The starter works in a Flutter app on Android, iOS, macOS, Windows and Linux. The server runs in the main isolate, with the same beans as the widgets: a local API, a companion server for other devices, a page served to a browser on the same machine.

- **`127.0.0.1` by default.** An app opens no port to the network unless `server.address` says so (`server.address=0.0.0.0`).
- **Do not block the UI.** `HttpServer`'s I/O is asynchronous, but heavy synchronous work in a handler blocks the UI too. Move it into another isolate with the [task executor](../../spring-core-dart/isolates/task-executor.md).
- **One isolate.** `server.isolates.*` is ignored in a Flutter app, with a warning. See [A pool of isolates](isolates.md#in-a-flutter-app).
- **In the background** the context pauses: the server stops and frees the port. It starts again when the app comes back. `spring.flutter.lifecycle.pause-in-background=false` keeps it running.
- **Platform permissions:**
  - macOS: the `com.apple.security.network.server` entitlement;
  - Android: the `INTERNET` permission in the release manifest;
  - iOS: binding beyond localhost asks the user for local network access (`NSLocalNetworkUsageDescription` in `Info.plist`).
- **The web** has no server sockets, and the starter's module is `native` only: in a browser build the generated application does not list it, so the app starts without a server and carries none of the starter's code (see [Modules of one platform](../../spring-core-dart-generator/optimizations/build-conditions.md#modules-of-one-platform)). A context that names the module by hand in a browser must run no server (`spring.main.web-application-type=none`); otherwise the start fails with:

```text
spring_boot_starter_web has no web server on this platform: the web has no server sockets. Run the server on the VM or in a Flutter app on mobile or desktop, or set spring.main.web-application-type=none.
```

## In Spring (Java)

```java
@SpringBootApplication
public class ShopApplication {
  public static void main(String[] args) {
    SpringApplication.run(ShopApplication.class, args);
  }
}
```

```properties
server.port=8080
server.address=127.0.0.1
server.servlet.context-path=/shop
```

Differences that matter:

- The server is `dart:io`'s `HttpServer`, not Tomcat, Jetty or Undertow. HTTP/1.1 only; `server.http2.enabled` is not read.
- `server.servlet.context-path` is `server.context-path`. The old name (any key under `server.servlet.`) stops the start and names the new key.
- `server.max-http-request-body-size` is this starter's own key.
- `spring.main.web-application-type` only knows `none`. There is no `servlet` or `reactive`.
- `spring.main.register-shutdown-hook` is `false` by default.
- A Flutter app listens on `127.0.0.1` by default.
- There are no `server.tomcat.*`, `server.jetty.*` or `server.undertow.*` keys, and no `server.max-http-request-header-size`.

## See also

- [TLS (HTTPS)](ssl.md)
- [Compression](compression.md)
- [Timeouts](timeouts.md)
- [Overload](overload.md)
- [A pool of isolates](isolates.md)
- [Behind a reverse proxy](reverse-proxy.md)
- [Shutdown](shutdown.md)
- [Handler mappings](handler-mappings.md)
- [WebSocket](websocket.md)
- [All properties](../properties.md)
- [Testing](../testing.md)
- [@ConfigurationProperties](../../spring-core-dart/config/configuration-properties.md)
- [Data sizes](../../spring-core-dart/conversion/data-size.md)
- [Context events](../../spring-core-dart/events/context-events.md)
- [Logging](../../spring-core-dart/logging/index.md)
