Middlewares in AdonisJS
Middlewares in AdonisJS
Middlewares in AdonisJS are functions or classes that execute logic before or after handling an HTTP request. They can intercept requests, modify request or response objects, perform authentication, and more.
Creating a Middleware
Middlewares are typically created as classes with a handle
method that defines the middleware logic.
Example AuthMiddleware
Here's an example of an AuthMiddleware
class that performs authentication and redirects unauthenticated users.
Important! Middlewares are registered in the start/kernel.ts
file. Registering Middlewares
ctx
is the HTTP context object, which contains information about the incoming request, such as the request method, URL, headers, session, inertia, auth...
import type { HttpContext } from "@adonisjs/core/http";
import type { NextFn } from "@adonisjs/core/types/http";
import type { Authenticators } from "@adonisjs/auth/types";
import User from "#common/models/user";
export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = '/auth/login';
async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: (keyof Authenticators)[]
} = {}
) {
await ctx.auth.authenticateUsing(options.guards, { loginRoute: this.redirectTo });
// Check if user information is incomplete and not navigating to OTP route
if (!User.isInformationComplete(ctx.auth.user!) && !ctx.request.url().includes("otp")) {
return ctx.response.redirect().toRoute('otp.next-step');
}
return next();
}
}
Registering Middlewares
Middlewares can be registered in the start/kernel.ts
file.
export const middleware = router.named({
guest: () => import('#common/middleware/guest_middleware'),
auth: () => import('#auth/auth_middleware'),
})
Middleware Properties
- handle: The
handle
method is invoked for each incoming HTTP request. It performs authentication using AdonisJS auth, redirects unauthorized requests, and ensures complete user information for specific routes.
Usage in Routes
Middlewares can be applied globally, to specific routes, or to groups of routes in the route definitions.
Example Usage in Routes
import router from "@adonisjs/core/services/router";
import AccountController from "./controllers/account_controller";
import { middleware } from "#start/kernel";
import AuthMiddleware from "./middleware/AuthMiddleware";
router.group(() => {
router.get("/", [AccountController, "update"]).as("account.update");
}).prefix("/account").use([middleware.auth()]);
export default router;
- Middleware Application: The
AuthMiddleware
is applied to routes within the/account
prefix to enforce authentication.
Benefits of Using Middleware
- Authentication: Middlewares like
AuthMiddleware
handle authentication logic, ensuring only authenticated users access protected routes. - Request Manipulation: Modify request or response objects, perform logging, or enforce specific behaviors across routes.
- Flexibility: Middlewares can be customized and reused across different parts of your application, promoting code reusability and maintainability.
See more
Middleware in AdonisJS provides a powerful mechanism for intercepting and processing HTTP requests, allowing you to enforce rules, manipulate requests, and enhance security and functionality in your application.