Photo by Magnus Engø on Unsplash
What is middleware?
Middleware is widely used typically on backend servers and REST APIs. Almost every single request you used to load up this page had some form of middleware. Every request to a server, whether that be GET, POST, PUT or anything else always gets put into middleware.
So what is it? Middleware is the wrapper around the core function of a request. Say you send a new message on a social media platform. Your POST request goes through an authentication middleware first to see if your allowed to see this page. It takes a JWT token or a session id to send from your browser which is then authenticated in the middleware.
What can middleware do?
Middleware can be used to validate data format, authenticate users, or provide security protection to the server. Middleware is used everywhere on the web. The Django framework has built in clickjacking protection, CRSF protection, GZIP, https, authentication, security, common, caching, and more forms of middleware they use to build out their APIs.
Actual Example of middleware
In this example I will be using a Golang REST API built with the framework of fiber
package middleware
import (
"github.com/NikSchaefer/go-fiber/handlers"
"github.com/NikSchaefer/go-fiber/model"
"github.com/gofiber/fiber/v2"
)
func Authenticated(c *fiber.Ctx) error {
json := new(model.Session)
if err := c.BodyParser(json); err != nil {
return c.SendStatus(fiber.StatusBadRequest)
}
user, status := handlers.GetUser(json.Sessionid)
if status != 0 {
return c.SendStatus(status)
}
c.Locals("user", user)
return c.Next()
}
What's going on here? First the request parses the bytes into a JSON Session Model. If it fails it returns a bad request. Then with the sessionid I retrieve the user of the sessionid and if it fails in any way return the request with the proper status code. Finally I set the user in c.Locals("user") to be accessed by the request or other middleware.
This middleware is called authenticated middleware because to access the actual request it requires a sessionid to be sent and the JSON and for it to be valid to a user. It also gives the request access to that user without having to query the database for it.
Comments