An HTTP server
suggest changeDart can run an HTTP server with nothing but the standard library: dart:io has HttpServer, which accepts connections, parses HTTP/1.1 and gives you a stream of requests. For bigger apps most people use Shelf, a small library from the Dart team that sits on top of HttpServer and adds composable handlers, middleware and routing.
This article covers:
- a minimal server with
HttpServer - reading the request: method, path, query, headers, body
- writing the response, and the mistakes that leave clients hanging
- routing with pattern matching, JSON, body size limits, error handling
- serving static files and server settings
- concurrency, streaming responses, and using all CPU cores
- graceful shutdown
- the same things with Shelf,
shelf_routerandshelf_static - testing
Related articles go deeper on specific topics: HTTP middleware, REST APIs, File uploads, CORS, WebSockets and TLS and HTTPS. For the client side, see HTTP Request.
Packages used in the later examples (the first ones need only dart:io):
dart pub add shelf shelf_router shelf_static http path
dart pub add dev:test
The examples were run with Dart 3.13, shelf 1.4.3, shelf_router 1.1.5, shelf_static 1.2.0, http 1.6.0 and path 1.9.
A minimal server
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
print('Listening on http://${server.address.host}:${server.port}');
await for (final HttpRequest request in server) {
print('${request.method} ${request.uri}');
request.response
..headers.contentType = ContentType.text
..write('Hello, world!\n');
await request.response.close();
}
}
HttpServer.bind opens a listening socket and returns a Future<HttpServer>. The server is a Stream<HttpRequest>, so await for handles requests one after another as they arrive. For each request you set the status and headers on request.response, write the body, and close the response, which sends it.
Run it and call it with curl from another terminal:
$ dart run bin/server.dart
Listening on http://127.0.0.1:62005
GET /hello?name=dart
$ curl -i http://127.0.0.1:62005/hello?name=dart
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
transfer-encoding: chunked
x-content-type-options: nosniff
Hello, world!
The x-frame-options, x-xss-protection and x-content-type-options headers come from server.defaultResponseHeaders, which dart:io adds to every response; you can change them (shown later). transfer-encoding: chunked is used because we didn't set a contentLength.
With await for, a handler that awaits something slow would hold up the following requests. server.listen(handler) calls the handler for every request without waiting for the previous one to finish, so that's what real servers use. The rest of the examples use listen and, to be self-contained, start the server on port 0 and send requests to it from the same program:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((HttpRequest request) async {
request.response
..headers.contentType = ContentType.text
..write('Hello, world!\n');
await request.response.close();
});
final client = HttpClient();
final request = await client.get('localhost', server.port, '/');
final response = await request.close();
print('status: ${response.statusCode}');
print('content-type: ${response.headers.contentType}');
print('body: ${await response.transform(utf8.decoder).join()}');
client.close();
await server.close();
}
Output:
status: 200
content-type: text/plain; charset=utf-8
body: Hello, world!
Addresses and ports
bind argument |
Meaning |
|---|---|
InternetAddress.loopbackIPv4 or '127.0.0.1' |
only this machine can connect (good for development) |
InternetAddress.anyIPv4 or '0.0.0.0' |
all IPv4 interfaces (what you need in a container or on a server) |
InternetAddress.anyIPv6 |
all interfaces, IPv6 and, by default, IPv4 too (v6Only: false) |
'localhost' |
resolved first, then bound to the first address found |
port 0 |
the OS picks a free port, read it back from server.port |
shared: true |
several isolates can bind the same address and port, see below |
A deployed server usually reads the port from an environment variable: int.parse(Platform.environment['PORT'] ?? '8080'). See Environment variables.
The request
HttpRequest gives you everything the client sent:
import 'dart:convert';
import 'dart:io';
Future<void> handle(HttpRequest request) async {
print('method: ${request.method}');
print('uri: ${request.uri}');
print('path: ${request.uri.path}');
print('segments: ${request.uri.pathSegments}');
print('query: ${request.uri.queryParameters}');
print('all tags: ${request.uri.queryParametersAll['tag']}');
print('requestedUri: ${request.requestedUri}');
print('content-type: ${request.headers.contentType?.mimeType}');
print('length: ${request.contentLength}');
print('user-agent: ${request.headers.value(HttpHeaders.userAgentHeader)}');
print('remote: ${request.connectionInfo?.remoteAddress.address}');
print('http version: ${request.protocolVersion}');
// HttpRequest is a Stream<Uint8List>: decode and join it to read the body.
final body = await utf8.decoder.bind(request).join();
final data = jsonDecode(body) as Map<String, dynamic>;
print('body: $data');
request.response.statusCode = HttpStatus.noContent;
await request.response.close();
}
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen(handle);
final client = HttpClient()..userAgent = 'demo/1.0';
final uri = Uri.parse('http://localhost:${server.port}/api/notes?tag=a&tag=b&limit=10');
final request = await client.postUrl(uri);
request.headers.contentType = ContentType.json;
request.write(jsonEncode({'title': 'Buy milk', 'done': false}));
final response = await request.close();
await response.drain<void>();
print('client got ${response.statusCode}');
client.close();
await server.close();
}
Output:
method: POST
uri: /api/notes?tag=a&tag=b&limit=10
path: /api/notes
segments: [api, notes]
query: {tag: b, limit: 10}
all tags: [a, b]
requestedUri: http://localhost:59359/api/notes?tag=a&tag=b&limit=10
content-type: application/json
length: -1
user-agent: demo/1.0
remote: 127.0.0.1
http version: 1.1
body: {title: Buy milk, done: false}
client got 204
Notes:
request.uriis the path and query as sent by the client.requestedUriadds the scheme and host (from theHostheader) to make it absolute.queryParameterskeeps only the last value of a repeated parameter,queryParametersAllkeeps all of them.request.headers.value(name)returns a single header value (it throws if the header occurs more than once),request.headers[name]returns a list. Header names are case-insensitive. The HTTP headers article covers headers in depth.contentLengthis -1 when the client didn't sendContent-Length, as here, whereHttpClientused chunked encoding.HttpRequestis aStream<Uint8List>of body bytes. It can be read only once. Decode it withutf8.decoder.bind(request).join(), or collect bytes with aBytesBuilderfor binary data. For multipart form data see File uploads.
Writing the response
request.response is an HttpResponse, which is an IOSink:
| What | How |
|---|---|
| status | response.statusCode = HttpStatus.created (default 200) |
| content type | response.headers.contentType = ContentType.json or ContentType('text', 'html', charset: 'utf-8') |
| other headers | response.headers.set('cache-control', 'no-store'), add for repeated headers |
| body text | response.write(text), encoded with the charset of the content type (UTF-8 for ContentType.json and ContentType.text) |
| body bytes | response.add(bytes), or await response.addStream(stream) |
| redirect | await response.redirect(Uri.parse('/login')) (302 by default, closes the response) |
| finish | await response.close() |
Two rules:
- Always close the response, on every code path, including errors. A response that is never closed leaves the client waiting until it times out.
- Set status and headers before writing the body. The first
writelocks them, and changing them afterwards throws:
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((request) async {
final res = request.response;
res.write('partial output');
try {
res.statusCode = 500;
} on StateError catch (e) {
print('StateError: ${e.message}');
}
await res.close();
});
final r = await http.get(Uri.parse('http://localhost:${server.port}/'));
print('client got ${r.statusCode}: ${r.body}');
await server.close();
}
Output:
StateError: Header already sent
client got 200: partial output
This matters for error handling: once a handler has started writing, a failure can no longer turn into a 500 response.
Routing, JSON and errors
dart:io has no router, but Dart 3 pattern matching on a (method, pathSegments) record makes a decent one for small servers. This example is a small JSON API for notes:
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
final notes = <int, String>{1: 'Buy milk'};
var nextId = 2;
Future<void> sendJson(HttpResponse response, int status, Object? data) async {
response
..statusCode = status
..headers.contentType = ContentType.json
..write(jsonEncode(data));
await response.close();
}
class PayloadTooLarge implements Exception {}
Future<Object?> readJson(HttpRequest request, {int maxBytes = 64 * 1024}) async {
// Reject early when the client announces a big body...
if (request.contentLength > maxBytes) throw PayloadTooLarge();
// ...and keep counting, because chunked bodies have no length up front.
final builder = BytesBuilder(copy: false);
await for (final chunk in request) {
builder.add(chunk);
if (builder.length > maxBytes) throw PayloadTooLarge();
}
return jsonDecode(utf8.decode(builder.takeBytes()));
}
Future<void> handle(HttpRequest request) async {
final res = request.response;
switch ((request.method, request.uri.pathSegments)) {
case ('GET', ['notes']):
await sendJson(res, 200, [
for (final MapEntry(:key, :value) in notes.entries) {'id': key, 'text': value}
]);
case ('GET', ['notes', final id]):
final text = notes[int.tryParse(id)];
if (text == null) return sendJson(res, 404, {'error': 'no note $id'});
await sendJson(res, 200, {'id': int.parse(id), 'text': text});
case ('POST', ['notes']):
final body = await readJson(request);
if (body case {'text': String text} when text.isNotEmpty) {
final id = nextId++;
notes[id] = text;
res.headers.set(HttpHeaders.locationHeader, '/notes/$id');
await sendJson(res, 201, {'id': id, 'text': text});
} else {
await sendJson(res, 400, {'error': 'expected {"text": "..."}'});
}
case ('DELETE', ['notes', final id]):
final removed = notes.remove(int.tryParse(id));
res.statusCode = removed == null ? 404 : 204;
await res.close();
case (_, ['notes', ...]):
res.headers.set(HttpHeaders.allowHeader, 'GET, POST, DELETE');
await sendJson(res, 405, {'error': 'method not allowed'});
default:
await sendJson(res, 404, {'error': 'not found'});
}
}
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((request) async {
try {
await handle(request);
} on PayloadTooLarge {
request.response.persistentConnection = false;
await sendJson(request.response, 413, {'error': 'body too large'});
} on FormatException {
await sendJson(request.response, 400, {'error': 'invalid JSON'});
} catch (e) {
// Anything else is a bug: answer 500 instead of leaving the client hanging.
print('error: $e');
try {
await sendJson(request.response, 500, {'error': 'internal error'});
} catch (_) {
// Headers were already sent; nothing more we can do.
}
}
});
final base = 'http://localhost:${server.port}';
Future<void> show(Future<http.Response> f) async {
final r = await f;
final location = r.headers['location'];
print('${r.statusCode} ${r.body}${location == null ? '' : ' (location: $location)'}');
}
await show(http.get(Uri.parse('$base/notes')));
await show(http.post(Uri.parse('$base/notes'), body: jsonEncode({'text': 'Walk dog'})));
await show(http.post(Uri.parse('$base/notes'), body: jsonEncode({'title': 'oops'})));
await show(http.post(Uri.parse('$base/notes'), body: '{not json'));
await show(http.post(Uri.parse('$base/notes'), body: 'x' * 100000));
await show(http.get(Uri.parse('$base/notes/2')));
await show(http.delete(Uri.parse('$base/notes/1')));
await show(http.put(Uri.parse('$base/notes/2')));
await show(http.get(Uri.parse('$base/notes')));
await show(http.get(Uri.parse('$base/nope')));
await server.close();
}
Output:
200 [{"id":1,"text":"Buy milk"}]
201 {"id":2,"text":"Walk dog"} (location: /notes/2)
400 {"error":"expected {\"text\": \"...\"}"}
400 {"error":"invalid JSON"}
413 {"error":"body too large"}
200 {"id":2,"text":"Walk dog"}
204
405 {"error":"method not allowed"}
200 [{"id":2,"text":"Walk dog"}]
404 {"error":"not found"}
How it works:
case ('GET', ['notes', final id])matches a GET request to/notes/<anything>and binds the second path segment toid.['notes', ...]matches/notesfollowed by any number of segments, which is used for the 405 response with anAllowheader.if (body case {'text': String text} when text.isNotEmpty)validates the decoded JSON and extracts the field in one step. See Pattern matching.readJsonlimits the body size. Without a limit, a client can send gigabytes and the server will happily buffer them in memory. It checkscontentLengthfirst, and also counts bytes because a chunked body has no length up front.- The wrapper in
listenturns exceptions into JSON error responses: 413 for a too large body, 400 for malformed JSON, 500 for everything else. Without it, an exception in an async handler is an unhandled error, which crashes the whole server process. - The 413 response sets
persistentConnection = false. The server didn't read the rest of the body, so the connection can't be reused for another request and it's closed after the response.
When the routes and the cross-cutting concerns (logging, auth, CORS) multiply, Shelf, shown later, is easier to grow. The REST APIs article has a fuller REST example.
Serving static files and server settings
To serve files, map the URL path to a path inside a root directory, refuse anything that escapes it, and stream the file into the response:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
const mimeTypes = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
};
Future<void> serveFile(HttpRequest request, String root) async {
final res = request.response;
var relative = p.normalize(Uri.decodeComponent(request.uri.path).substring(1));
if (relative == '.') relative = 'index.html';
final path = p.join(root, relative);
// Refuse '../' tricks that would escape the root directory.
if (!p.isWithin(root, path)) {
res.statusCode = HttpStatus.forbidden;
return res.close();
}
final file = File(path);
if (!await file.exists()) {
res.statusCode = HttpStatus.notFound;
res.write('not found\n');
return res.close();
}
final type = mimeTypes[p.extension(path)] ?? 'application/octet-stream';
res.headers
..set(HttpHeaders.contentTypeHeader, type)
..contentLength = await file.length();
// Stream the file instead of reading it into memory.
await res.addStream(file.openRead());
await res.close();
}
Future<void> main() async {
final root = p.absolute('public');
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0)
..serverHeader = 'notes/1.0'
..idleTimeout = const Duration(seconds: 30)
..autoCompress = true;
server.defaultResponseHeaders
..remove('x-xss-protection', '1; mode=block')
..add('cache-control', 'no-cache');
server.listen((request) => serveFile(request, root));
final client = http.Client();
for (final path in ['/', '/style.css', '/missing.txt', '/..%2Fpubspec.yaml']) {
final r = await client.get(Uri.parse('http://localhost:${server.port}$path'));
print('$path -> ${r.statusCode} ${r.headers['content-type']} '
'server=${r.headers['server']} cache=${r.headers['cache-control']}');
print(' ${r.body.trim()}');
}
client.close();
await server.close();
}
Output:
/ -> 200 text/html; charset=utf-8 server=notes/1.0 cache=no-cache
<h1>Home</h1>
/style.css -> 200 text/css; charset=utf-8 server=notes/1.0 cache=no-cache
body { color: navy; }
/missing.txt -> 404 text/plain; charset=utf-8 server=notes/1.0 cache=no-cache
not found
/..%2Fpubspec.yaml -> 403 text/plain; charset=utf-8 server=notes/1.0 cache=no-cache
Things to note:
p.isWithin(root, path)rejects..tricks after decoding and normalizing the path. This check is essential: without it,GET /..%2F..%2Fetc%2Fpasswdreads files outside the root.res.addStream(file.openRead())streams the file in chunks, so big files don't have to fit in memory. SettingcontentLengthreplaces chunked encoding with aContent-Lengthheader.serverHeadersets theServerresponse header (none by default).idleTimeoutcloses keep-alive connections that have been idle that long (default 120 seconds).autoCompress = truegzips response bodies when the client sendsAccept-Encoding: gzip.defaultResponseHeadersholds headers added to every response. Here the obsoletex-xss-protectionis removed andcache-controladded.
In real projects, shelf_static (below) does this with caching headers (Last-Modified, If-Modified-Since), range requests and MIME type detection.
Concurrency and streaming responses
A Dart server runs in a single isolate (one thread) by default, but it still handles many requests at once: while one handler awaits a database query, a file read or a timer, the event loop runs other handlers. What blocks everyone is CPU-heavy synchronous code in a handler; move that to another isolate with Isolate.run (see Isolates).
A response doesn't have to be produced all at once either. With bufferOutput = false and flush(), each chunk goes to the client as soon as it's written:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> handle(HttpRequest request) async {
final res = request.response;
switch (request.uri.path) {
case '/slow':
// Waiting on I/O (a timer here) doesn't block other requests.
await Future<void>.delayed(const Duration(milliseconds: 500));
res.write('slow done\n');
case '/stream':
res.headers.contentType = ContentType.text;
res.bufferOutput = false; // send each write right away
for (var i = 1; i <= 3; i++) {
res.write('tick $i\n');
await res.flush();
await Future<void>.delayed(const Duration(milliseconds: 200));
}
}
await res.close();
}
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen(handle);
final base = 'http://localhost:${server.port}';
final watch = Stopwatch()..start();
final bodies = await Future.wait([
for (var i = 0; i < 5; i++) http.read(Uri.parse('$base/slow')),
]);
print('${bodies.length} slow requests took ${watch.elapsedMilliseconds} ms');
// Read a streamed response chunk by chunk as it arrives.
final client = http.Client();
final response = await client.send(http.Request('GET', Uri.parse('$base/stream')));
watch.reset();
await for (final line in response.stream.transform(utf8.decoder).transform(const LineSplitter())) {
print('${(watch.elapsedMilliseconds / 100).round() * 100} ms: $line');
}
client.close();
await server.close();
}
Output:
5 slow requests took 578 ms
0 ms: tick 1
200 ms: tick 2
400 ms: tick 3
Five requests that each wait 500 ms finished in well under 5 × 500 ms because they ran concurrently. The streamed response arrived in three pieces, 200 ms apart. This is the basis of long-running downloads and server-sent events; for two-way messaging, use WebSockets.
Using all CPU cores
To use more than one core, run the server in several isolates that all bind the same port with shared: true. The OS distributes incoming connections among them:
import 'dart:io';
import 'dart:isolate';
import 'package:http/http.dart' as http;
Future<void> serve((int id, int port) args) async {
final (id, port) = args;
// shared: true lets several isolates bind the same address and port;
// incoming connections are spread across them.
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port, shared: true);
await for (final request in server) {
request.response.write('isolate $id\n');
await request.response.close();
}
}
Future<void> main() async {
// Bind once on port 0 to get a free port, then share it.
final first = await HttpServer.bind(InternetAddress.loopbackIPv4, 0, shared: true);
final port = first.port;
first.listen((request) async {
request.response.write('isolate 0\n');
await request.response.close();
});
final workers = <Isolate>[];
for (var id = 1; id < 4; id++) {
workers.add(await Isolate.spawn(serve, (id, port)));
}
await Future<void>.delayed(const Duration(milliseconds: 300)); // let them bind
final counts = <String, int>{};
for (var i = 0; i < 200; i++) {
// A new client per request means a new connection, so the load spreads.
final body = await http.read(Uri.parse('http://localhost:$port/'));
counts.update(body.trim(), (n) => n + 1, ifAbsent: () => 1);
}
print((counts.keys.toList()..sort()).map((k) => '$k: ${counts[k]}').join('\n'));
for (final w in workers) {
w.kill();
}
await first.close();
}
Output:
isolate 0: 50
isolate 1: 50
isolate 2: 50
isolate 3: 50
Isolates don't share memory, so each one has its own copy of any in-memory state (caches, counters, the notes map from earlier). State that must be shared belongs in a database or in something like Redis. How evenly connections are spread depends on the OS; with keep-alive, all requests on one connection go to the same isolate.
Graceful shutdown
When a server is stopped (Ctrl+C, or SIGTERM from a process manager like Docker or systemd), it should stop accepting new connections and let in-flight requests finish instead of dropping them:
import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final started = Completer<void>();
server.listen((request) async {
if (!started.isCompleted) started.complete();
await Future<void>.delayed(const Duration(milliseconds: 500));
request.response.write('finished ${request.uri.path}\n');
await request.response.close();
});
var stopping = false;
Future<void> shutdown(String why) async {
if (stopping) return;
stopping = true;
print('shutting down ($why)');
// Stop accepting new connections. Open connections are left alone,
// and idle keep-alive ones are closed.
await server.close();
// close() doesn't wait for in-flight requests, so wait for them, up to a limit.
final deadline = DateTime.now().add(const Duration(seconds: 5));
while (server.connectionsInfo().active > 0 && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
await server.close(force: true); // drop whatever is still open
print('server closed');
}
// Ctrl+C. Add ProcessSignal.sigterm too on Linux/macOS (not supported on Windows).
final sigint = ProcessSignal.sigint.watch().listen((_) => shutdown('SIGINT'));
final base = 'http://localhost:${server.port}';
final inFlight = http.read(Uri.parse('$base/report'));
await started.future; // the server is now busy with /report
final done = shutdown('demo'); // what the SIGINT handler would do
try {
await http.read(Uri.parse('$base/late'));
} on http.ClientException catch (e) {
print('new request failed: ${e.message.split(',').first}');
}
print('in-flight request got: ${(await inFlight).trim()}');
await done;
await sigint.cancel();
}
Output:
shutting down (demo)
server closed
new request failed: The remote computer refused the network connection
in-flight request got: finished /report
server.close() stops listening and closes idle connections, but the future it returns doesn't wait for active requests. To give them time to finish, the code polls connectionsInfo() until no connection is active or a deadline passes, then calls close(force: true) to drop the rest. The Signals and graceful shutdown article covers signal handling in detail.
Shelf basics
Shelf replaces "write to a mutable response" with "return a response". A handler is a function from Request to Response (or Future<Response>), and shelf_io.serve runs it on a dart:io HttpServer:
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
Response handler(Request request) {
print('method=${request.method} url=${request.url} '
'requestedUri=${request.requestedUri}');
final name = request.url.queryParameters['name'] ?? 'world';
return Response.ok('Hello, $name!\n');
}
Future<void> main() async {
// shelf_io.serve binds an HttpServer and adapts each HttpRequest to a shelf Request.
final server = await shelf_io.serve(handler, 'localhost', 0);
print('Serving at http://${server.address.host}:${server.port}');
final r = await http.get(Uri.parse('http://localhost:${server.port}/greet?name=Dart'));
print('${r.statusCode} ${r.headers['content-type']} ${r.body.trim()}');
await server.close();
}
Output:
Serving at http://localhost:59365
method=GET url=greet?name=Dart requestedUri=http://localhost:59365/greet?name=Dart
200 text/plain; charset=utf-8 Hello, Dart!
request.url is relative to the handler: it has no leading /, and when a handler is mounted under a prefix, the prefix is removed. requestedUri is the full original URL. Request and Response are immutable, so headers and bodies are set in the constructor or with change(). Read the body with await request.readAsString() or request.read() (a byte stream).
Response has named constructors for common statuses: Response.ok, Response.notFound, Response.forbidden, Response.badRequest, Response.internalServerError, Response.found(location), Response.movedPermanently(location), plus Response(status, ...) for any other. The body can be a String, a list of bytes or a Stream<List<int>>.
A complete Shelf app
A typical app combines three packages: shelf_router for routing with path parameters, shelf_static for files, and Shelf's Pipeline for middleware:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';
const jsonHeaders = {'content-type': 'application/json'};
Response jsonResponse(Object? data, {int status = 200}) =>
Response(status, body: jsonEncode(data), headers: jsonHeaders);
final notes = <int, String>{1: 'Buy milk'};
Router buildApi() => Router()
..get('/notes', (Request request) {
return jsonResponse([
for (final MapEntry(:key, :value) in notes.entries) {'id': key, 'text': value}
]);
})
// <id|[0-9]+> captures a path parameter, passed as an extra String argument.
..get('/notes/<id|[0-9]+>', (Request request, String id) {
final text = notes[int.parse(id)];
return text == null
? jsonResponse({'error': 'no note $id'}, status: 404)
: jsonResponse({'id': int.parse(id), 'text': text});
})
..post('/notes', (Request request) async {
final body = jsonDecode(await request.readAsString());
if (body case {'text': String text}) {
final id = notes.keys.fold(0, (a, b) => a > b ? a : b) + 1;
notes[id] = text;
return jsonResponse({'id': id, 'text': text}, status: 201);
}
return jsonResponse({'error': 'expected {"text": "..."}'}, status: 400);
});
Future<void> main() async {
final router = Router()
..get('/health', (Request request) => Response.ok('ok'))
..mount('/api/', buildApi().call);
// Cascade tries handlers in order until one returns something other than 404/405.
final app = Cascade()
.add(router.call)
.add(createStaticHandler('public', defaultDocument: 'index.html'))
.handler;
final handler = const Pipeline().addMiddleware(logRequests()).addHandler(app);
final server = await shelf_io.serve(handler, 'localhost', 0);
final client = http.Client();
final base = 'http://localhost:${server.port}';
Future<void> show(Future<http.Response> f) async {
final r = await f;
print(' -> ${r.statusCode} ${r.headers['content-type']}: ${r.body.trim()}');
}
await show(client.get(Uri.parse('$base/health')));
await show(client.get(Uri.parse('$base/api/notes')));
await show(client.post(Uri.parse('$base/api/notes'), body: jsonEncode({'text': 'Walk dog'})));
await show(client.get(Uri.parse('$base/api/notes/2')));
await show(client.get(Uri.parse('$base/api/notes/abc')));
await show(client.get(Uri.parse('$base/')));
await show(client.get(Uri.parse('$base/style.css')));
client.close();
await server.close();
}
Output:
2026-10-17T22:43:10.468201 0:00:00.003702 GET [200] /health
-> 200 text/plain; charset=utf-8: ok
2026-10-17T22:43:10.497208 0:00:00.010382 GET [200] /api/notes
-> 200 application/json: [{"id":1,"text":"Buy milk"}]
2026-10-17T22:43:10.516597 0:00:00.016403 POST [201] /api/notes
-> 201 application/json: {"id":2,"text":"Walk dog"}
2026-10-17T22:43:10.535119 0:00:00.002764 GET [200] /api/notes/2
-> 200 application/json: {"id":2,"text":"Walk dog"}
2026-10-17T22:43:10.541432 0:00:00.006355 GET [404] /api/notes/abc
-> 404 text/plain; charset=utf-8: Not Found
2026-10-17T22:43:10.552783 0:00:00.005830 GET [200] /
-> 200 text/html: <h1>Home</h1>
2026-10-17T22:43:10.561855 0:00:00.000663 GET [200] /style.css
-> 200 text/css: body { color: navy; }
What each part does:
Routermatches method and path. A pattern like<id|[0-9]+>captures a path parameter, which is passed to the handler as an extraStringargument.router.mount('/api/', handler)sends everything under/api/to another handler, here a second router, with/apiremoved fromrequest.url.Cascadetries handlers in order and returns the first response that isn't 404 or 405. Here, anything the router doesn't know goes to the static handler. That's why/api/notes/abc(which doesn't match[0-9]+) produced the static handler's plain-textNot Found.createStaticHandler('public', defaultDocument: 'index.html')serves files frompublic/with MIME types,Last-Modifiedand range support, and guards against path traversal.Pipeline().addMiddleware(logRequests())adds request logging around everything. Error handling, authentication, CORS and other middleware are covered in HTTP middleware and CORS.
A Shelf handler that throws an exception isn't fatal: shelf_io logs it and answers with a 500 response. You'll still usually want error middleware that returns a proper JSON error.
Testing
Because a Shelf handler is just a function, most tests can call it directly without any network. For end-to-end tests, start a real server on port 0 in setUp:
// lib/app.dart
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
Handler buildHandler() {
final router = Router()
..get('/hello/<name>', (Request request, String name) => Response.ok('Hello, $name!'));
return router.call;
}
// test/app_test.dart (in a package named httpsrv)
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:httpsrv/app.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:test/test.dart';
void main() {
final handler = buildHandler();
test('handler can be called directly', () async {
final response = await handler(Request('GET', Uri.parse('http://localhost/hello/Ann')));
expect(response.statusCode, 200);
expect(await response.readAsString(), 'Hello, Ann!');
});
group('over real HTTP', () {
late HttpServer server;
setUp(() async => server = await shelf_io.serve(handler, 'localhost', 0));
tearDown(() => server.close(force: true));
test('unknown route is 404', () async {
final r = await http.get(Uri.parse('http://localhost:${server.port}/nope'));
expect(r.statusCode, 404);
});
});
}
$ dart run test/app_test.dart
+2: All tests passed!
A dart:io handler can be tested the same way as the end-to-end test: bind on port 0 and send requests with package:http, as all the examples in this article do.
dart:io or Shelf?
dart:io HttpServer |
Shelf | |
|---|---|---|
| Dependencies | none | shelf (+ shelf_router, shelf_static, ...) |
| Handler | writes to a mutable HttpResponse |
returns an immutable Response |
| Middleware | do it yourself | Pipeline, createMiddleware, many packages |
| Routing | pattern matching or your own code | shelf_router |
| Testing | needs a real socket | call the handler directly |
| Good for | tiny tools, health endpoints, learning, maximum control | most web apps and APIs |
Frameworks like Dart Frog and Serverpod are built on top of these same pieces. To deploy, compile the server to a native executable with dart compile exe bin/server.dart (see Compiling to executables), bind to InternetAddress.anyIPv4 and the port from the environment, and put it behind a reverse proxy, or terminate TLS in Dart as shown in TLS and HTTPS.
Summary
| Task | How |
|---|---|
| Start a server | final server = await HttpServer.bind(InternetAddress.anyIPv4, port); |
| Handle requests concurrently | server.listen((HttpRequest request) async { ... }) |
| Path and query | request.uri.pathSegments, request.uri.queryParameters |
| Read the body | await utf8.decoder.bind(request).join() (with a size limit) |
| Send a response | set statusCode and headers, write/add, then await response.close() |
| Route | switch ((request.method, request.uri.pathSegments)) { case ('GET', ['notes', final id]): ... } |
| Stream a file | await response.addStream(File(path).openRead()) |
| Stream chunks | response.bufferOutput = false, write, await response.flush() |
| Use all cores | HttpServer.bind(..., shared: true) in several isolates |
| Shut down gracefully | await server.close(), wait while connectionsInfo().active > 0, close(force: true) |
| Shelf server | await shelf_io.serve(handler, InternetAddress.anyIPv4, port) |
| Shelf routing | Router()..get('/notes/<id>', (Request r, String id) => ...) |
| Static files | createStaticHandler('public', defaultDocument: 'index.html') |
| Combine handlers | Cascade().add(a).add(b).handler |
Always close the response, limit body sizes, catch errors in dart:io handlers, and validate paths before touching the file system.