Middleware
- Dart course
- Advanced
- Lesson 27/83
- 5 min
Learn middleware with shelf Middleware.
Middleware
A middleware wraps a handler and intercepts the request/response flow. Signature: Middleware logMiddleware(Handler inner) => (req) async { print('request'); return await inner(req); }.
Typical uses: logging, authentication, CORS, error handling. Middlewares are chained; each layer can decide whether to call the next.
shelf's Pipeline API: Pipeline().addMiddleware(log).addHandler(app). This builds a modular handler chain.
The logRequests middleware
shelf ships a ready logRequests() middleware. It prints each request's method and path to the console, waits for the response and prints the elapsed time.
Usage: var handler = Pipeline().addMiddleware(logRequests()).addHandler(appHandler);. You pass this handler to shelf_io.
To write your own middleware, follow the pattern (Handler inner) => (Request req) async { ... }.
Practice Define a simple logging middleware
Add import 'package:shelf/shelf.dart';. Define Handler logMiddleware(Handler inner) => (Request req) async { print('istek geldi'); return await inner(req); };. Define Response app(Request r) => Response.ok('ok');. Make main async; add var wrapped = logMiddleware(app);, var resp = await wrapped(Request('GET', Uri.parse('http://localhost/'))); and print(resp.statusCode);.
Starter code
void main() {
// add shelf import; define logMiddleware and app
// call the wrapped handler; print statusCode
}Sample solution
import 'package:shelf/shelf.dart';
Handler logMiddleware(Handler inner) => (Request req) async {
print('istek geldi');
return await inner(req);
};
Response app(Request r) => Response.ok('ok');
void main() async {
var wrapped = logMiddleware(app);
var resp = await wrapped(Request('GET', Uri.parse('http://localhost/')));
print(resp.statusCode);
}Expected output
istek geldi 200
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Middleware uses
| Term | Meaning |
|---|---|
Logging |
Print every request |
Auth |
Check token |
CORS |
Add headers |
Error |
Wrap try/catch |
2 What does a middleware do?
- Starts a new server
- Ignores the request
- Wraps a handler and intercepts the flow Correct answer
- Deletes the response
Explanation: a middleware wraps a handler and intercepts the request/response flow.
3 Add middleware to Pipeline
Pipeline().____(logRequests()).addHandler(app);
Pipeline().addMiddleware(logRequests()).addHandler(app);
Explanation: addMiddleware adds a middleware to the pipeline.