DartAdvanced 2 min read

Dart Shelf middleware and CORS: handle cross-cutting behavior

Compose request handling while keeping cross-origin browser policy separate from authorization.

On this page

Middleware wraps a handler so concerns such as error conversion, request timing and browser-origin policy can be applied consistently. Keep the order explicit: a logger outside an error converter can observe the final response status instead of only an exception.

Understand the composition boundary

final app = const Pipeline()
    .addMiddleware(handleProblems())
    .addHandler(router.call);

This fragment uses the project’s error middleware and router. The middleware awaits the inner result, maps expected ApiProblem values to stable JSON and keeps unexpected exception details out of the response. Real operational logging should record useful context on the server without copying secrets or entire request bodies.

Add CORS only for the clients you intend to support

A browser running at one origin may need permission to call another origin. Inspect the Origin header and allow an explicit configured origin. Handle supported preflight methods and headers and return the required allow headers on the actual response too.

When reflecting an approved origin, include appropriate Vary behavior so a shared cache does not reuse the wrong origin response. Do not combine wildcard Allow-Origin with credentialed requests. The exact credential, cookie and CSRF design depends on the authentication model.

CORS is a browser response policy, not authentication. A non-browser client can call an unauthenticated endpoint even when the browser refuses to expose the response. Use the identity and ownership lesson for access control.

Make logs useful and bounded

Record method, normalized route, status, duration and a request correlation ID where needed. Avoid logging bearer tokens, passwords, full query strings containing sensitive data or private payloads. Distinguish a rejected request from a failed server operation so monitoring can identify the actual failing layer.

Exercise

Write handler tests for an allowed origin, a rejected origin and a preflight request. Verify an invalid JSON request still receives a structured error through the middleware stack. Explain why adding CORS cannot fix a missing-route or expired-token failure.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.