Middleware typedef

Middleware = Handler Function(Handler next)

A function which creates a new Handler by wrapping a Handler.

You can extend the functions of a Handler by wrapping it in Middleware that can intercept and process a request before it is sent to a handler, a response after it is sent by a handler, or both.

Because Middleware consumes a Handler and returns a new Handler, multiple Middleware instances can be composed together to offer rich functionality.

Common uses for middleware include caching, logging, and authentication.

Middleware that captures exceptions should be sure to pass HijackExceptions on without modification.

A simple Middleware can be created using createMiddleware.

Basic Middleware

Middleware loggingMiddleware = (Handler next) {
  return (Request req) async {
    print('Request: ${req.method} ${req.url}');
    final result = await next(req);
    print('Completed request');
    return result;
  };
};

Using createMiddleware

// Request processing
final middleware = createMiddleware(
  onRequest: (request) {
    print('Processing: ${request.url}');
    return null; // Continue to handler
  },
);

// Response processing
final middleware = createMiddleware(
  onResponse: (response) {
    print('Status: ${response.statusCode}');
    return response;
  },
);

// Error handling
final middleware = createMiddleware(
  onError: (error, stackTrace) {
    print('Error: $error');
    return Response.internalServerError(
      body: Body.fromString('An error occurred'),
    );
  },
);

Authentication Middleware

final authMiddleware = createMiddleware(
  onRequest: (request) {
    final auth = request.headers.authorization;
    if (auth == null) {
      return Response.unauthorized(
        body: Body.fromString('Authentication required'),
      );
    }
    return null; // Continue to handler
  },
);

Implementation

typedef Middleware = Handler Function(Handler next);