middleware static method

Future middleware(
  1. HttpRequest request,
  2. Future<void> next()
)

Applies CORS headers to the response and handles preflight requests.

For all requests, this method sets the standard response headers used by the framework's default CORS policy.

If the incoming request method is OPTIONS, the middleware responds with 200 OK, closes the response, and does not continue the pipeline.

For all other request methods, control is passed to next.

Parameters:

  • request: The active HTTP request.
  • next: The next middleware or route handler in the pipeline.

Example:

await CorsMiddleware.middleware(request, () async {
  request.response.write(jsonEncode({'status': 'ok'}));
});

Implementation

static Future<dynamic> middleware(
  HttpRequest request,
  Future<void> Function() next,
) async {
  // Add CORS headers to response
  request.response.headers
    ..set('Access-Control-Allow-Origin', '*')
    ..set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    ..set('Access-Control-Allow-Headers', 'Content-Type, Range')
    ..set('Access-Control-Expose-Headers', 'Content-Length, Content-Range');

  // Handle preflight OPTIONS request
  if (request.method == 'OPTIONS') {
    request.response.statusCode = HttpStatus.ok;
    await request.response.close();
    return;
  }

  await next();
}