AdonisJs. Named Middlewares with passing props

Making life o lot easier by reducing copy-pasting logic using named Middleware

Let’s consider and example.

You want to check user ROLE (admin, user, viewer, editor, ect) in your application and in specific Routes.

Off course, you can implement this checking by inserting lines of code in each of your Controller index, show, store, update, etc functions where it needed, like:

But, as you can see, there will be to much copy-pasting each time you will need this checks.

There is a better solution.

Named middleware

Main difference between global and named middleware is that global middleware will be used in each request, but named middleware (auth, for example) can be used there, where it’s needed.

And you can pass props to that middleware as well.

Creating named middleware

1. Use adonis cli command

make:middleware

If you choose For HTTP requests, middleware will be created only with handle function:

Selecting For Websocket requests will create middleware with wsHandle function, with the exactly same code.

As you understand selecting For both HTTP and Websocket requests with create middleware with both functions.

2. Registration

Next, you need to register your middleware in the /start/kernel.js file by adding path string with your custom name:

3. Start using it

Let create a simple console.log() functionality in our RoleDetector.js file:

And now you can start using it in your application with those Routes you needed. Let’s see an example:

Here we are saying that we want to use our created RoleDetector middleware (by name, that we defined in namedMiddleware) and passing ‘admin’ property.

Let’s see console result:

You can pass as many properties as you like:

Console result would be:

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store