Basics / Middleware
A Functional Approach
Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.
For example, Archery includes a middleware that verifies the user of your application is authenticated. If the user is unauthenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed deeper into the application.
Defining Middleware
To create a new middleware, you only need to define a function matching the HttpMiddleware signature, which accepts an HttpRequest and a next callback.
Future<dynamic> ensureAdmin(
HttpRequest request,
Future<void> Function() next
) async {
final user = await request.user;
if (user == null || !user.isAdmin) {
return request.forbidden();
}
// Continue to the next middleware or route handler
await next();
}
The next() call behaves as an asynchronous pipeline. You can even perform actions after the request has been fully processed by placing code after await next().
Applying Middleware
Middleware can be applied to individual static/dynamic routes or entire route groups.
Route-Level Middleware
You can attach middleware directly when defining a route by passing an array to the optional middleware parameter:
router.get('/dashboard', (request) async {
return request.view('dashboard.index');
}, middleware: [ensureAdmin]);
Group-Level Middleware
More commonly, you will want to apply middleware to a large collection of routes. This is achieved using the router.group method:
router.group(
prefix: '/admin',
middleware: [Sessions.middleware, ensureAdmin],
routes: () {
router.get('/settings', (request) async {
return request.view('admin.settings');
});
router.get('/users', (request) async {
return request.view('admin.users.index');
});
},
);
By default, the webRoutes scaffold includes the Sessions.middleware to ensure your session values and CSRF tokens operate reliably across HTML responses.
Included Middleware
Archery ships with core middleware that powers essential web functions:
Sessions.middleware: Initializes the global session engine and manages guest sessions.VerifyCsrfToken: Defends against cross-site request forgery.Cors: Manages Cross-Origin Resource Sharing.FlashMessages: Allows lifecycle management of ephemeral data intended for single request-redirect pipelines.