Middleware

  • Implementing a middleware is very simple, for example:
my-nodestack-app
├── src
│   ├── middleware
│   │   │   │── example.js
│   ├── routes
│   │   │── middleware
│   │   │   │── index.js
├── ndsk.config.js
└── package.json
module.exports = {
    name:"example",      // middleware name
    handler:async (request,h)=>{
        const id = request.query.id;
        if(id === '1'){
            h.next({name:"this is example moddleware"});
        }else if(id === '2'){
            return 'end---'
        }else{
            return h.redirect('https://ndsk.dev');
        }
    }
}
export const options = {
    plugins:{
       middleware:{
            example:true
       } 
    }
};
export default (request)=>{
    return request.middleware.example
}
  • We created the src/middleware/example.js middleware file and named the current middleware as: example. In the routes/middleware/index.js route, set middleware.example:true to enable the current middleware and use request.middleware.example to get the value returned by the current middleware

  • If request.query.id is equal to 1, return h.next(value) to continue to the next step. If request.query.id is equal to 2, directly return to end the current request. If request.query.id is equal to , redirect to 'https://ndsk.dev

  • Visit http://localhost:3000/middleware?id=1

  • Visit http://localhost:3000/middleware?id=2

  • Visit http://localhost:3000/middleware?id=3

To enable middleware you need to configure example:true in the route

export const options = {
    plugins:{
       middleware:{
            example:true            //Middleware Name
       } 
    }
};
  • You can use request.route.settings.plugins.middleware to get the middleware configuration
  • Middleware can only handle business logic when requesting and responding

Next

Plugin