HTTP middleware
suggest changeMiddleware is code that runs around every request handler in a server. It sees the request before the handler does and the response after the handler returns, so it's the place for things that apply to many routes:
- logging and timing
- authentication and authorization
- turning exceptions into proper error responses
- adding headers (security headers, CORS, request ids)
- rate limiting, body size limits, signature checks
In Dart, server-side middleware almost always means Shelf, the HTTP server library from the Dart team that most Dart backends (and frameworks like Dart Frog) build on. This article covers:
- what a Shelf
Middlewareis and howPipelineorders them createMiddlewarefor simple cases- passing data to handlers through the request context
- short-circuiting: authentication and route-specific middleware
- error handling middleware
- middleware that reads the request body
- stateful middleware: a rate limiter
- built-in and third-party middleware, and the order to put them in
- middleware with plain
dart:io - testing middleware without a server
Packages used:
dart pub add shelf shelf_router http crypto
dart pub add dev:test
The examples were run with Dart 3.13, shelf 1.4.3, shelf_router 1.1.5, http 1.6.0 and crypto 3.0.7. See REST APIs for Shelf basics.
Handlers and middleware
Shelf has two core types:
typedef Handler = FutureOr<Response> Function(Request request);
typedef Middleware = Handler Function(Handler innerHandler);
A handler takes a request and returns a response. A middleware takes a handler and returns a new handler that wraps it. Inside the wrapper you can:
- inspect or change the request before calling the inner handler
- not call the inner handler at all and return a response yourself
- inspect or change the response the inner handler returned
- catch exceptions the inner handler threw
Pipeline chains middleware and ends with a handler. The first middleware added is the outermost one. This program shows the order in which the code runs:
import 'package:shelf/shelf.dart';
Middleware trace(String name) {
return (Handler inner) {
return (Request request) async {
print('$name: before');
final response = await inner(request);
print('$name: after (status ${response.statusCode})');
return response;
};
};
}
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(trace('outer'))
.addMiddleware(trace('inner'))
.addHandler((Request request) {
print('handler: ${request.method} /${request.url}');
return Response.ok('hello');
});
// A Handler is just a function, so we can call it without a server.
final response = await handler(Request('GET', Uri.parse('http://localhost/hello')));
print('body: ${await response.readAsString()}');
}
Output:
outer: before
inner: before
handler: GET /hello
inner: after (status 200)
outer: after (status 200)
body: hello
Middleware nest like layers of an onion: the request travels inwards through them in the order they were added, and the response travels back out in reverse order. Pipeline().addMiddleware(a).addMiddleware(b).addHandler(h) is the same as a(b(h)).
Shelf's Request and Response are immutable. To modify one, call change(), which returns a copy with new headers, context or body.
createMiddleware
For middleware that only needs to look at the request, or only at the response, createMiddleware saves the nested closures:
requestHandlerruns before the inner handler. Returnnullto continue, or aResponseto answer right awayresponseHandlergets the inner handler's response and returns the (possibly changed) responseerrorHandlergets exceptions thrown by the inner handler
import 'package:shelf/shelf.dart';
/// Adds headers to every response that comes back from the inner handler.
final securityHeaders = createMiddleware(
responseHandler: (Response response) => response.change(headers: {
'x-frame-options': 'DENY',
'referrer-policy': 'no-referrer',
}),
);
/// Rejects requests with methods the app doesn't support.
final allowedMethods = createMiddleware(
requestHandler: (Request request) {
const allowed = {'GET', 'HEAD', 'POST'};
if (!allowed.contains(request.method)) {
return Response(405, body: 'method not allowed', headers: {'allow': allowed.join(', ')});
}
return null; // null means: continue to the inner handler
},
);
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(allowedMethods)
.addMiddleware(securityHeaders)
.addHandler((Request request) => Response.ok('ok'));
for (final method in ['GET', 'DELETE']) {
final response = await handler(Request(method, Uri.parse('http://localhost/')));
print('$method -> ${response.statusCode} ${await response.readAsString()}');
for (final name in ['allow', 'x-frame-options', 'referrer-policy']) {
if (response.headers[name] case final value?) print(' $name: $value');
}
}
}
Output:
GET -> 200 ok
x-frame-options: DENY
referrer-policy: no-referrer
DELETE -> 405 method not allowed
allow: GET, HEAD, POST
The 405 response has no security headers. allowedMethods is the outer middleware, so when it answers by itself the request never reaches securityHeaders. Even within a single createMiddleware, the responseHandler is not applied to a response returned by the requestHandler. If a header must be on every response, put the middleware that adds it before (outside of) anything that can short-circuit.
Passing data to handlers: the request context
Middleware often works something out that handlers need: the request id, the logged-in user, a database transaction. Request.context is a read-only Map<String, Object> for this. request.change(context: {...}) returns a request whose context has the new entries merged in.
Shelf asks that context keys be namespaced, for example with your package name, so different middleware don't overwrite each other's values. Shelf itself uses keys like shelf.io.connection_info, and shelf_router uses shelf_router/params.
This server adds a request id and a timing header. The request id is reused if the client (or a load balancer) already sent one:
import 'dart:math';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
final _random = Random.secure();
String newRequestId() =>
List.generate(8, (_) => _random.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
/// Gives every request an id: reuses the client's X-Request-Id if present,
/// stores it in the request context and echoes it in the response.
Middleware requestId() {
return (Handler inner) {
return (Request request) async {
final id = request.headers['x-request-id'] ?? newRequestId();
final updated = request.change(context: {'myapp.requestId': id});
final response = await inner(updated);
return response.change(headers: {'x-request-id': id});
};
};
}
/// Measures how long the inner handler took and reports it in Server-Timing.
Middleware timing() {
return (Handler inner) {
return (Request request) async {
final watch = Stopwatch()..start();
final response = await inner(request);
final ms = watch.elapsedMicroseconds / 1000;
return response.change(headers: {'server-timing': 'app;dur=${ms.toStringAsFixed(1)}'});
};
};
}
extension RequestIdExt on Request {
String get requestId => context['myapp.requestId'] as String;
}
Future<Response> hello(Request request) async {
await Future<void>.delayed(const Duration(milliseconds: 20)); // pretend to work
return Response.ok('hello, your request id is ${request.requestId}\n');
}
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(requestId())
.addMiddleware(timing())
.addHandler(hello);
// Port 0 asks the OS for any free port.
final server = await io.serve(handler, 'localhost', 0);
final url = Uri.parse('http://localhost:${server.port}/');
for (final headers in [<String, String>{}, {'x-request-id': 'from-client-42'}]) {
final response = await http.get(url, headers: headers);
print(response.body.trim());
print(' x-request-id: ${response.headers['x-request-id']}');
print(' server-timing: ${response.headers['server-timing']}');
}
await server.close();
}
Output:
hello, your request id is 263432a6c648d9cc
x-request-id: 263432a6c648d9cc
server-timing: app;dur=24.8
hello, your request id is from-client-42
x-request-id: from-client-42
server-timing: app;dur=29.1
An extension getter like request.requestId hides the string key and the cast, so handlers don't depend on how the middleware stores the value. Server-Timing is shown in the browser's network panel next to the request.
To make the request id appear in every log line written while handling the request, without passing it around, run the inner handler inside a zone. See "Adding context with zones" in Logging.
Short-circuiting: authentication
Authentication middleware checks credentials and either returns 401 Unauthorized without calling the handler, or passes the request on with the user stored in the context. The example also shows how to apply middleware to only part of the app: shelf_router's mount() accepts any handler, including a Pipeline.
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';
class User {
final String name;
final bool isAdmin;
const User(this.name, {this.isAdmin = false});
}
// In a real app: a database lookup, a session, or a verified JWT.
const tokens = {
'alice-token': User('alice', isAdmin: true),
'bob-token': User('bob'),
};
/// Requires a valid `Authorization: Bearer <token>` header.
Middleware authenticate() {
return (Handler inner) {
return (Request request) {
final header = request.headers['authorization'] ?? '';
final token = header.startsWith('Bearer ') ? header.substring(7) : null;
final user = tokens[token];
if (user == null) {
return Response.unauthorized('missing or invalid token\n',
headers: {'www-authenticate': 'Bearer'});
}
return inner(request.change(context: {'myapp.user': user}));
};
};
}
/// Must run after authenticate(): it reads the user it stored.
Middleware requireAdmin() {
return (Handler inner) {
return (Request request) {
final user = request.context['myapp.user'] as User;
if (!user.isAdmin) return Response.forbidden('admins only\n');
return inner(request);
};
};
}
User currentUser(Request request) => request.context['myapp.user'] as User;
Future<void> main() async {
final api = Router()
..get('/me', (Request r) => Response.ok('you are ${currentUser(r).name}\n'));
final admin = Router()
..get('/stats', (Request r) => Response.ok('42 users\n'));
final app = Router()
// Public: no middleware.
..get('/health', (Request r) => Response.ok('ok\n'))
// Logged-in users only.
..mount('/api/', const Pipeline().addMiddleware(authenticate()).addHandler(api.call))
// Admins only: both middleware, in this order.
..mount(
'/admin/',
const Pipeline()
.addMiddleware(authenticate())
.addMiddleware(requireAdmin())
.addHandler(admin.call),
);
final server = await io.serve(app.call, 'localhost', 0);
final base = 'http://localhost:${server.port}';
Future<void> get(String path, [String? token]) async {
final response = await http.get(Uri.parse('$base$path'),
headers: {if (token != null) 'authorization': 'Bearer $token'});
print('${path.padRight(13)} ${(token ?? '-').padRight(12)} '
'${response.statusCode} ${response.body.trim()}');
}
await get('/health');
await get('/api/me');
await get('/api/me', 'wrong');
await get('/api/me', 'bob-token');
await get('/admin/stats', 'bob-token');
await get('/admin/stats', 'alice-token');
await server.close();
}
Output:
/health - 200 ok
/api/me - 401 missing or invalid token
/api/me wrong 401 missing or invalid token
/api/me bob-token 200 you are bob
/admin/stats bob-token 403 admins only
/admin/stats alice-token 200 42 users
Notes:
- 401 vs 403.
401 Unauthorizedmeans "I don't know who you are" and should include aWWW-Authenticateheader.403 Forbiddenmeans "I know who you are, and you're not allowed". - Order matters.
requireAdmin()depends on the user thatauthenticate()stored, so it must come after it. If it ran first, theas Usercast would throw. - The mounted handler sees paths relative to the mount point: inside
api, the route is/me, not/api/me. - For real token checking see JWT, and for cookie-based logins see Sessions. Both articles plug into the same kind of middleware.
Because a Middleware is just a function from Handler to Handler, you can also apply one to a single route by calling it on that route's handler. Route parameters are then read with the request.params extension from shelf_router:
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
final requireKey = createMiddleware(
requestHandler: (request) =>
request.headers['x-api-key'] == 's3cret' ? null : Response.unauthorized('bad key'),
);
Future<void> main() async {
final router = Router()
..get('/users/<id>', (Request r, String id) => Response.ok('public profile $id'))
// A Middleware is a function from Handler to Handler: call it on one handler.
..delete('/users/<id>',
requireKey((Request r) => Response.ok('deleted ${r.params['id']}')));
for (final (method, key) in [('GET', null), ('DELETE', null), ('DELETE', 's3cret')]) {
final response = await router.call(Request(method, Uri.parse('http://localhost/users/7'),
headers: {'x-api-key': ?key}));
print('$method key=$key -> ${response.statusCode} ${await response.readAsString()}');
}
}
Output:
GET key=null -> 200 public profile 7
DELETE key=null -> 401 bad key
DELETE key=s3cret -> 200 deleted 7
{'x-api-key': ?key} uses Dart's null-aware map element: the entry is left out when key is null.
Error handling middleware
If a handler throws, shelf_io logs the error and replies with a plain-text 500 Internal Server Error. An API usually wants something better: JSON errors, the right status code for known errors, and no stack traces sent to clients. A middleware with a try/catch around the inner handler does that in one place:
import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
/// An error that should be reported to the client as-is.
class ApiException implements Exception {
final int status;
final String message;
ApiException(this.status, this.message);
}
Response jsonResponse(int status, Object body) => Response(status,
body: jsonEncode(body), headers: {'content-type': 'application/json'});
/// Turns exceptions thrown by inner handlers into JSON error responses.
Middleware handleErrors() {
return (Handler inner) {
return (Request request) async {
try {
return await inner(request);
} on HijackException {
rethrow; // used by WebSockets; must reach the server adapter
} on ApiException catch (e) {
return jsonResponse(e.status, {'error': e.message});
} on FormatException catch (e) {
return jsonResponse(400, {'error': 'bad input: ${e.message}'});
} catch (e, st) {
// Log the details, but don't leak them to the client.
print('ERROR ${request.method} /${request.url}: $e\n'
'${st.toString().split('\n').first}');
return jsonResponse(500, {'error': 'internal server error'});
}
};
};
}
final _books = {1: 'Essential Dart'};
Future<void> main() async {
final router = Router()
..get('/books/<id>', (Request request, String id) {
final book = _books[int.parse(id)]; // throws FormatException for "abc"
if (book == null) throw ApiException(404, 'no book with id $id');
return jsonResponse(200, {'id': id, 'title': book});
})
..get('/crash', (Request request) {
final List<int> empty = [];
return Response.ok('${empty.first}'); // throws StateError
});
final handler = const Pipeline().addMiddleware(handleErrors()).addHandler(router.call);
for (final path in ['books/1', 'books/7', 'books/abc', 'crash']) {
final response = await handler(Request('GET', Uri.parse('http://localhost/$path')));
print('/$path -> ${response.statusCode} ${await response.readAsString()}');
}
}
Output:
/books/1 -> 200 {"id":"1","title":"Essential Dart"}
/books/7 -> 404 {"error":"no book with id 7"}
/books/abc -> 400 {"error":"bad input: Invalid radix-10 number"}
ERROR GET /crash: Bad state: No element
#0 List.first (dart:core-patch/growable_array.dart:352:5)
/crash -> 500 {"error":"internal server error"}
Things to get right:
return await inner(request), notreturn inner(request). Withoutawait, an asynchronous handler's error is not thrown inside thetryblock, and thecatchnever sees it.- Rethrow
HijackException. WebSocket handlers (shelf_web_socket) take over the connection by throwing it, and it must reachshelf_io.createMiddleware'serrorHandlerandlogRequests()already rethrow it for you. - Throwing an exception like
ApiExceptionfrom deep inside your code, then mapping it to a status in one middleware, keeps handlers short. See Custom exception. - Use a real logger instead of
print, and include the request id from the previous section so you can match the client's error to the log line.
Middleware that reads the body
A request body is a stream and can be read only once. Middleware that needs the body, for example to verify a webhook signature, must hand the inner handler a request with a fresh copy. Otherwise the handler fails with:
Bad state: The 'read' method can only be called once on a shelf.Request/shelf.Response object.
request.change(body: bytes) fixes that. This middleware checks an HMAC-SHA256 signature over the raw body, the scheme used by GitHub, Stripe and many other webhook senders:
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:shelf/shelf.dart';
const secret = 'webhook-secret';
String sign(List<int> body) =>
'sha256=${Hmac(sha256, utf8.encode(secret)).convert(body)}';
/// Compares without stopping at the first difference, so response time
/// doesn't reveal how much of a forged signature was correct.
bool constantTimeEquals(String a, String b) {
if (a.length != b.length) return false;
var diff = 0;
for (var i = 0; i < a.length; i++) {
diff |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
}
return diff == 0;
}
/// Verifies an X-Signature header computed over the raw request body.
Middleware verifySignature({int maxBytes = 1024 * 1024}) {
return (Handler inner) {
return (Request request) async {
// Read the whole body, with a size limit.
final bytes = <int>[];
await for (final chunk in request.read()) {
bytes.addAll(chunk);
if (bytes.length > maxBytes) return Response(413, body: 'body too large');
}
final expected = sign(bytes);
final actual = request.headers['x-signature'] ?? '';
if (!constantTimeEquals(expected, actual)) {
return Response.forbidden('bad signature');
}
// The body stream has been consumed: give the inner handler a fresh copy.
return inner(request.change(body: bytes));
};
};
}
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(verifySignature())
.addHandler((Request request) async {
final event = jsonDecode(await request.readAsString()) as Map<String, dynamic>;
return Response.ok('got event ${event['type']}');
});
final body = utf8.encode('{"type":"payment.succeeded"}');
for (final signature in [sign(body), 'sha256=forged']) {
final response = await handler(Request(
'POST',
Uri.parse('http://localhost/webhook'),
body: body,
headers: {'x-signature': signature},
));
print('${response.statusCode} ${await response.readAsString()}');
}
}
Output:
200 got event payment.succeeded
403 bad signature
The signature must be computed over the exact bytes that were sent. Decoding the JSON and encoding it again can change whitespace or key order and break the check, which is one more reason to do this in middleware, before any handler touches the body. Buffering is fine for small bodies like webhooks. For file uploads, stream instead (see File uploads).
Stateful middleware: rate limiting
The function that creates the middleware runs once, so variables declared there live as long as the server and are shared by all requests. That's where a rate limiter keeps its counters. The client's IP address comes from the HttpConnectionInfo that shelf_io stores in the context:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
/// Allows [limit] requests per client per [window] (fixed window counter).
Middleware rateLimit({required int limit, required Duration window}) {
// State lives in the closure, shared by all requests.
final counts = <String, ({DateTime start, int count})>{};
return (Handler inner) {
return (Request request) async {
// shelf_io stores the socket info in the context.
final info = request.context['shelf.io.connection_info'] as HttpConnectionInfo?;
final client = info?.remoteAddress.address ?? 'unknown';
final now = DateTime.now();
var entry = counts[client];
if (entry == null || now.difference(entry.start) >= window) {
entry = (start: now, count: 0);
}
entry = (start: entry.start, count: entry.count + 1);
counts[client] = entry;
final remaining = limit - entry.count;
if (remaining < 0) {
final retryAfter = window - now.difference(entry.start);
return Response(429,
body: 'too many requests\n',
headers: {'retry-after': '${(retryAfter.inMilliseconds / 1000).ceil()}'});
}
final response = await inner(request);
return response.change(headers: {'x-ratelimit-remaining': '$remaining'});
};
};
}
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(rateLimit(limit: 3, window: const Duration(seconds: 10)))
.addHandler((Request request) => Response.ok('ok\n'));
final server = await io.serve(handler, 'localhost', 0);
final url = Uri.parse('http://localhost:${server.port}/');
for (var i = 1; i <= 5; i++) {
final r = await http.get(url);
print('request $i: ${r.statusCode} ${r.body.trim()} '
'remaining=${r.headers['x-ratelimit-remaining']} retry-after=${r.headers['retry-after']}');
}
await server.close();
}
Output:
request 1: 200 ok remaining=2 retry-after=null
request 2: 200 ok remaining=1 retry-after=null
request 3: 200 ok remaining=0 retry-after=null
request 4: 429 too many requests remaining=null retry-after=10
request 5: 429 too many requests remaining=null retry-after=10
Dart runs the code between awaits without interruption, so the read-modify-write of counts needs no lock. But the state is per process: with several server instances or isolates, each has its own counters. Keep shared counters in Redis instead (INCR plus EXPIRE). A real limiter should also remove old entries so the map doesn't grow forever. Behind a reverse proxy, the socket address is the proxy's; use X-Forwarded-For only if you trust the proxy that sets it.
Built-in and third-party middleware
Shelf itself ships only one ready-made middleware, logRequests(), which prints one line per request (see Logging for sending it to package:logging). Others come from packages on pub.dev, for example:
| Need | Package |
|---|---|
CORS headers and preflight OPTIONS requests |
shelf_cors_headers (corsHeaders()) |
| Serving static files | shelf_static (a handler, often combined with Cascade) |
| WebSockets | shelf_web_socket (a handler) |
| Request/response gzip | HttpServer.autoCompress = true in dart:io, or your own middleware |
CORS middleware decides which other origins may call your API from a browser, and answers preflight OPTIONS requests by itself. Put it near the outside of the pipeline, before authentication, because browsers send preflight requests without credentials. The CORS article covers the details.
Putting it in order
A typical pipeline, from outside to inside:
- Logging sees the final status of every request, including errors turned into 500s.
- Headers that must be on every response (security headers, CORS, request id).
- Error handling, so exceptions from everything inside become responses that still pass through 1 and 2.
- Rate limiting, authentication and other checks that may short-circuit.
- The router.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';
class ApiException implements Exception {
final int status;
final String message;
ApiException(this.status, this.message);
}
Middleware handleErrors() => (inner) => (request) async {
try {
return await inner(request);
} on HijackException {
rethrow;
} on ApiException catch (e) {
return Response(e.status, body: jsonEncode({'error': e.message}));
} catch (e) {
return Response.internalServerError(body: jsonEncode({'error': 'internal error'}));
}
};
final securityHeaders = createMiddleware(
responseHandler: (response) => response.change(headers: {
'x-frame-options': 'DENY',
'referrer-policy': 'no-referrer',
}),
);
final jsonContentType = createMiddleware(
responseHandler: (response) => response.headers.containsKey('content-type')
? response
: response.change(headers: {'content-type': 'application/json'}),
);
Future<void> main() async {
final router = Router(
notFoundHandler: (Request r) => Response.notFound(jsonEncode({'error': 'not found'})),
)
..get('/hello', (Request r) => Response.ok(jsonEncode({'message': 'hello'})))
..get('/secret', (Request r) => throw ApiException(403, 'nope'))
..get('/bug', (Request r) => throw StateError('oops'));
final handler = const Pipeline()
.addMiddleware(logRequests()) // 1. outermost: sees the final response
.addMiddleware(securityHeaders) // 2. applies to every response, errors too
.addMiddleware(jsonContentType) // 3.
.addMiddleware(handleErrors()) // 4. innermost: turns exceptions into responses
.addHandler(router.call);
final server = await io.serve(handler, 'localhost', 0);
for (final path in ['/hello', '/secret', '/bug', '/missing']) {
final r = await http.get(Uri.parse('http://localhost:${server.port}$path'));
print(' -> ${r.statusCode} ${r.headers['content-type']} '
'x-frame-options=${r.headers['x-frame-options']} ${r.body}');
}
await server.close();
}
Output:
2026-10-17T21:38:33.511106 0:00:00.006160 GET [200] /hello
-> 200 application/json x-frame-options=DENY {"message":"hello"}
2026-10-17T21:38:33.548691 0:00:00.001202 GET [403] /secret
-> 403 application/json x-frame-options=DENY {"error":"nope"}
2026-10-17T21:38:33.564664 0:00:00.000605 GET [500] /bug
-> 500 application/json x-frame-options=DENY {"error":"internal error"}
2026-10-17T21:38:33.580784 0:00:00.000471 GET [404] /missing
-> 404 application/json x-frame-options=DENY {"error":"not found"}
Every response, including the error responses, got the JSON content type and the security headers, and every request was logged with its final status. If handleErrors() were first instead, logRequests() would log the StateError with a stack trace as an error, and the 500 response would have no security headers, because the exception would skip right past securityHeaders.
The router got a notFoundHandler that returns JSON. Its default 404 is the plain text Route not found without a content type, which jsonContentType would otherwise mislabel as JSON.
Middleware with plain dart:io
Without Shelf, the same idea works with dart:io's HttpServer: define a handler type and a middleware type as functions, and compose them. The difference is that HttpRequest is mutable and the response is written, not returned. So "after" code can only read what the handler already set (the status code), and can't change headers once the response has started:
import 'dart:convert';
import 'dart:io';
typedef IoHandler = Future<void> Function(HttpRequest request);
typedef IoMiddleware = IoHandler Function(IoHandler inner);
IoMiddleware logging() => (inner) => (request) async {
final watch = Stopwatch()..start();
await inner(request);
print('${request.method} ${request.uri} '
'${request.response.statusCode} ${watch.elapsedMilliseconds}ms');
};
IoMiddleware requireApiKey(String key) => (inner) => (request) async {
if (request.headers.value('x-api-key') != key) {
request.response.statusCode = HttpStatus.unauthorized;
request.response.write('bad api key\n');
await request.response.close();
return;
}
await inner(request);
};
/// Applies middleware so that the first one in the list is the outermost.
IoHandler compose(List<IoMiddleware> middleware, IoHandler handler) =>
middleware.reversed.fold(handler, (inner, m) => m(inner));
Future<void> main() async {
final handler = compose([logging(), requireApiKey('s3cret')], (request) async {
request.response.write('hello from dart:io\n');
await request.response.close();
});
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen(handler);
final client = HttpClient();
for (final key in ['s3cret', 'wrong']) {
final request = await client.get('localhost', server.port, '/hello');
request.headers.set('x-api-key', key);
final response = await request.close();
final body = await response.transform(utf8.decoder).join();
print('client got ${response.statusCode}: ${body.trim()}');
}
client.close();
await server.close();
}
Output (the server's log line and the client's line can come in either order, since both run concurrently):
GET /hello 200 11ms
client got 200: hello from dart:io
client got 401: bad api key
GET /hello 401 5ms
This is fine for a small tool. For anything bigger, Shelf's immutable request/response model makes middleware much easier to write correctly.
Testing middleware
Handlers are plain functions, so middleware can be tested by building a Request and calling the pipeline. No server, no ports. Put a recording handler at the end to check what the middleware passed on:
import 'package:shelf/shelf.dart';
import 'package:test/test.dart';
Middleware requireApiKey(String key) => (inner) => (request) {
if (request.headers['x-api-key'] != key) {
return Response.unauthorized('bad api key');
}
return inner(request.change(context: {'myapp.client': 'trusted'}));
};
void main() {
// The innermost handler records what it received.
Request? seen;
final handler = const Pipeline()
.addMiddleware(requireApiKey('s3cret'))
.addHandler((request) {
seen = request;
return Response.ok('ok');
});
setUp(() => seen = null);
Request get({Map<String, String> headers = const {}}) =>
Request('GET', Uri.parse('http://localhost/data'), headers: headers);
test('rejects a missing key without calling the handler', () async {
final response = await handler(get());
expect(response.statusCode, 401);
expect(seen, isNull);
});
test('passes valid requests through with context', () async {
final response = await handler(get(headers: {'x-api-key': 's3cret'}));
expect(response.statusCode, 200);
expect(await response.readAsString(), 'ok');
expect(seen!.context['myapp.client'], 'trusted');
});
}
$ dart test test/auth_test.dart
00:00 +0: rejects a missing key without calling the handler
00:00 +1: passes valid requests through with context
00:00 +2: All tests passed!
Middleware that depends on shelf_io context, like the rate limiter's shelf.io.connection_info, can be tested by passing that value in Request(..., context: {...}), or with a real server on port 0 and package:http, as in the earlier examples.
Summary
| Task | How |
|---|---|
| Write middleware | Middleware m = (Handler inner) => (Request req) async { ...; final res = await inner(req); ...; return res; } |
| Simple before/after hooks | createMiddleware(requestHandler: ..., responseHandler: ..., errorHandler: ...) |
| Chain middleware | const Pipeline().addMiddleware(a).addMiddleware(b).addHandler(h), a is outermost |
| Answer without calling the handler | return a Response instead of calling inner (or return it from requestHandler) |
| Pass data to handlers | request.change(context: {'myapp.key': value}), read request.context['myapp.key'] |
| Change a response | response.change(headers: {...}) |
| Apply to some routes only | router.mount('/api/', Pipeline()...addHandler(api.call)) or middleware(handler) |
| Catch handler errors | try { return await inner(req); }, rethrow HijackException |
| Read the body in middleware | read it, then inner(request.change(body: bytes)) |
| Client IP address | request.context['shelf.io.connection_info'] as HttpConnectionInfo |
| Request logging | logRequests() |
| Test | call the pipeline with Request('GET', Uri.parse(...)) |
Keep each middleware small and focused on one job, think about the order as layers (outside sees everything, inside sees only what got through), and always await the inner handler when you need to see its response or its errors.