Middlewares
Middlewares are functions that sit between the request and response cycle in a web application. They have access to the request and response objects, and can modify them or perform actions before passing control to the next middleware or route handler.
As of right now only the @sodacore/http
plugin implements middlewares, but other plugins may implement their own middleware systems in the future.
Usage
Their usage is dependent on the plugin that implements them, for example, in the HTTP plugin, middlewares can be applied globally, to a controller, or to a specific route.
We also use middlewares for dealing with WebSocket upgrades, as part of the @sodacore/ws
plugin, and the @sodacore/http
plugin offers a generic CorsMiddleware
class to allow for easy CORS handling, although this is mostly for testing, and real CORS handling should be done with blacklists, and potentially better handling of preflight requests.
Creating a middleware
There are two types of middlewares, global and local.
Global Middlewares
Global middlewares are like authentication guards to some extent, they offer a supports
method and a handle
method, the supports
method is called with the request and response objects, and should return a boolean indicating whether or not the middleware should be applied to the request. The handle
method is then called with the request and response objects and can actually execute the middleware logic.
import { GlobalMiddleware, type HttpContext, type IGlobalMiddleware } from '@sodacore/http';
@GlobalMiddleware()
export class MyMiddleware implements IGlobalMiddleware {
public async supports(ctx: HttpContext) {
// Only support GET requests.
return ctx.request.method === 'GET';
}
public async handle(ctx: HttpContext) {
// Log the request method and url.
console.log(`Request: ${ctx.request.method} ${ctx.request.url}`);
}
}
This will be applied to every request, but the supports
method will filter out any requests that are not GET
requests.
Local Middlewares
Local middlewares are simply just functions that are passed the same HttpContext
object as their only parameter, and must be assigned to a specific controller or method directly.
import { HttpContext } from '@sodacore/http';
export function LogPostRequests(ctx: HttpContext) {
if (ctx.request.method === 'POST') {
console.log(`POST Request: ${ctx.request.method} ${ctx.request.url}`);
}
}
As you can see this middleware is much simpler.
Conclusion
Middlewares can be used for a variety of things, such as logging, authentication, validation, etc... They are a powerful tool for building web applications, and can help keep your code clean and maintainable.