| Maybe im misunderstanding how people are building endpoints these days, but every post about this I see how it can bypass auth. Wouldn’t this bypass auth only for sites where auth is true/false? I’ve never worked on a site were auth is a boolean. Auth is always a relative. The middleware is only there to identify the user. Then when querying for objects, you query objects related to that user. Or if you are serving an admin page you check that the user is an admin. I honestly find it more astounding that people put an admin security check to check the url of a page and redirect away in a middleware and no security on the views themselves. Is this form of checking paths in middleware officially from NextJS or did people just get lazy? Seems like the worst way to build auth I could ever dream up across any framework or language. If a middleware is bypassed all endpoints should return empty responses. In my nextjs apps the middleware is simply a convenience method for the user if they are logged out they get redirected to the login page. But all api endpoints check for the active user and serve objects relative to the user. |
This is a common way to implement auth in many frameworks, not just JS ones. Off the top of my head I know that Laravel (PHP) does it this way. I guess you could call it “being lazy” but most people would refer to it using the age-old software engineering terms “don’t repeat yourself” and “separation of concerns.”
The authentication middleware can choose to redirect or not based on many things: did the user provide the correct credentials, does the user have the necessary permissions to access the requested resource, etc… And you can put all the logic for determining those many things in a single place, so that it can easily be updated. Individual routes can remain as they are, and you don’t have to worry about forgetting to implement some part of the auth checking logic on one of them.