Middleware
Building an application router with middleware
Dr Graeme StuartBuilding an application router with middleware
Dr Graeme StuartOur MVC application is nearly completes
We need to implement the router and middleware.
Arrays have a find method which returns the first element that returns true from the given callback function.
| |
Our routing logic can use this same pattern to find a matching route.
| |
To implement this, we need to maintain an array of routes..
The router class handles an array of routes. Each route matches a pattern and a method to a handler function.
| |
The handle function hands over to the first route that matches the request.
We create an instance of our application and register some routes.
| |
| |
The router handles all incoming requests.
Our MVC application is nearly completes
We need to implement the router and middleware.
Middleware functions wrap around the request handler.
| |
Middleware can execute code before and after the request handler completes.
Middleware functions receive a context object and a next function.
| |
GET /items
logged in as: myUsername
Access granted to protected route
status: 200
GET /styles.css
logged in as: myUsername
[2026-03-15 16:25:50] [GET] /styles.css 304
status: 304
GET /favicon.ico
logged in as: myUsername
Not found!
status: 404
They always return the result of passing the context into the next function.
Middleware functions can add information to the context. Here we add the session to the context.
| |
| |
| |
They can also shortcut the request and return a response early.
Middleware implementation relies on a recursive pattern
| |
calling the
usemethod adds middleware to the chain.
Using global middleware is simple. We just pass our functions into the
usemethod.
| |
However, we can’t require a session on every request.
To apply middleware selectively we need to pass functions when we register routes.
| |
Combining the global middleware with the route-based middleware gives a flexible system.
We can use middleware to extract and validate formData.
| |
The validation data are added to the context, along with the status code.
Middleware can now be passed to specific routes.
| |
Each route is defined as a chain of actions.
Our post handlers can be simplified by adding them to the middleware chain.
| |
The
createItemControllerchecks validation data and if validation fails, it simple hands over to the next middleware to render the errors in the form. If validation passes, it performs the action and returns a redirect.
We can add controllers as middleware.
| |
Now our application configuration determines the overall behaviour of our application.
If you have any questions, now is a good time to ask.
Thanks for listening
Dr Graeme Stuart