Middleware

Spark uses Shelf middleware, a functional pattern where middleware wraps handlers to add behavior. This gives you access to the entire Shelf ecosystem.

Creating Middleware

A middleware is a function that takes a `Handler` and returns a new `Handler`. This allows you to run code before and after the inner handler.

import 'package:shelf/shelf.dart';

Middleware authMiddleware() {
  return (Handler innerHandler) {
    return (Request request) async {
      // Pre-processing: check authorization
      final token = request.headers['authorization'];
      if (token == null) {
        return Response.forbidden('Unauthorized');
      }

      // Call the next handler in the chain
      final response = await innerHandler(request);

      // Post-processing (optional)
      return response;
    };
  };
}

Page Middleware

Override the `middleware` getter in your page to apply middleware to that route.

@Page(path: '/dashboard')
class DashboardPage extends SparkPage<void> {
  @override
  List<Middleware> get middleware => [
    authMiddleware(),
  ];

  @override
  Element render(void data, PageRequest request) {
    return div(['Welcome to the dashboard']);
  }
}

Endpoint Middleware

Use the `middleware` parameter in the `@Endpoint` annotation for API routes.

@Endpoint(path: '/api/users', method: 'GET', middleware: [authMiddleware()])
Future<Response> getUsers(Request request) async {
  // Only runs if authMiddleware allows
  return Response.ok('[]');
}