Please stop using middleware to protect your routes

3 pointsposted 10 hours ago
by markerz

1 Comments

codingdave

10 hours ago

When building up something small and new, sure, checking security in each route is quick and easy. But a time will come where your security, roles, and whatnot have evolved to the point that new features and roles would mean you need to go update every route. Aside from the tedium to do so, it introduces more changes which means more potential for mistakes. That is when middleware is better.

When you do get to that point, don't hard-code checks on whether the current user has the exact roles for that specific route. Instead, get more creative. Every app will have different needs, but I like to do all the setup for the auth checks when they first login, cache an array of their allowed routes on the server, and then you just check whether the cache has the current route on each request. (Yes, and clear that cache if their access changes mid-session.)

Doing so is not much code, performs well at scale, and you never have to touch the routes themselves when refactoring security, you just need to tweak that setup function.