In this tutorial, we will learn about Defining the AdonisJS Middleware Module, how Adonis supports this Middleware Module, and how to define this Middleware Module or how to make middleware for AdonisJS.

Middleware

Middleware is a series of functions that are executed during an HTTP request before it reaches the route handler for your application.

You can check our previous article: AdonisJS: REST API simple CRUD Operation. IF you want then buy a good, reliable, secure web hosting service  from here: click here

Also, every function in the chain has the ability to end the request or forward it to the next function for your application.

how-to-make-middleware-for-AdonisJS

Basic Example

The easy way to test a middleware is to attach it to the route using the Route.middleware following the below method. For example:

Route
.get('/users/:id', async () => {
return 'Show user'
})
.middleware(async (ctx, next) => {
console.log(`Inside middleware ${ctx.request.url()}`)
await next()
})

Middleware classes

Need to write middleware as inline functions are fine for some quick testing. However, we can recommend extracting the middleware logic to its own application file.

Now, you can create a new middleware by running the following Ace command.

node ace make:middleware LogRequest

# CREATE: app/Middleware/LogRequest.ts

About middleware class

Since Middleware classes are stored inside the app/Middleware directory and each file represents a single middleware.

So, every middleware class must implement the handle method to handle the HTTP request and call the next method to forward the request to the next middleware or the route handler. app/Middleware/LogRequest.ts

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class LogRequest {
public async handle(
{ request }: HttpContextContract,
next: () => Promise<void>
) {
console.log(`-> ${request.method()}: ${request.url()}`)
await next()
}
}

Now, you can terminate requests from the middleware by raising an exception or sending the response using the response.send method as follows below

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class Auth {
public async handle(
{ request, response }: HttpContextContract,
next: () => Promise<void>
) {
if (notAuthenticated) {
response.unauthorized({ error: 'Must be logged in' })
return
}

await next()
}
}

Registering the Middleware

To take effect for the middleware, and it must be registered as a global middleware or a named middleware inside the start/kernel.ts file like below

You can purchase your hosting from Cloudsurph.comCloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.

Global Middleware

In this, Global middleware is executed for all the HTTP requests in the same sequence as they are registered.

Also, you can register them as an array inside the start/kernel.ts file, as follows below:

Server.middleware.register([
() => import('@ioc:Adonis/Core/BodyParser'),
() => import('App/Middleware/LogRequest')
])

Named Middleware

The named middleware allows you to selectively apply middleware on your routes/group of your routes.

Also, you can begin by registering them with a unique name and later reference it on the route by that name as like below command start/kernel.ts

Server.middleware.registerNamed({
auth: () => import('App/Middleware/Auth')
})

Also, you can attach the auth middleware to a route in the following example.

Route
.get('dashboard', 'DashboardController.index')
.middleware('auth') //

This middleware can be applied to one or more multiple actions for resource routes and more about applying middleware to resourceful routes.

Here, you can also define multiple middleware on a route by passing them as an array or calling the middleware method multiple times like follows

Route
.get('dashboard', 'DashboardController.index')
.middleware(['auth', 'acl', 'throttle'])
Route
.get('dashboard', 'DashboardController.index')
.middleware('auth')
.middleware('acl')
.middleware('throttle')

Passing the config to named middleware

The named middleware also can accept runtime config through the handle method as the third argument like the following command

export default class Auth {
public async handle(
{ request, response }: HttpContextContract,
next: () => Promise<void>,
guards?: string[]
) {
await next()
}
}

Finally, in the above example, the Auth middleware accepts an optional guards’ array.

And the user of the middleware can pass the guards as follows in the below command

Route
.get('dashboard', 'DashboardController.index')
.middleware('auth:web,api')

If you want to know more about AdonisJS Model relationships then please visit AdonisJs main website.

If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.