Search code examples
node.jsexpressroutesmiddleware

Express Middleware


I'm a beginner in Express framework and having some difficulty with the code flow. I have following code in app.js

app.use('/', index);
app.use('/login', login);
app.use(require('./routes/authenticate_user'))
app.use('/user', userDetails);

Problem is that If a user enters an invalid route suppose '/wrong' then my middleware sends the response for that instead of app throwing 404 Not found. Is there something I'm missing?(looks obvious). Thanks for any help.


Solution

  • There are a couple choices for how/where you run the authentication middleware.

    1) You can run it immediately after any non-authenticated routes have been defined. This will give you a non-auth error for any route, whether it's a real route or not other than the few routes that the user is allowed to go to without authentication.

    2) You can manually add the middleware to each defined route that is supposed to have authentication such as:

    app.get('/something', yourAuthMiddleware, yourRouteHandler);
    

    This will run the auth check only on routes that are actually defined. This allows you to give a 404 rather than an auth error for routes that are not defined.

    The advantage of the first option (which is essentially how you have it now) is that a non-authenticated user doesn't even get to find out which routes are defined or not. If they're not authenticated, they don't get in at all except to the couple of routes that they are allowed to. In my opinion, this is the right design.

    The second option will let you give a 404 for a route that isn't defined, but it requires manually adding auth to each route or each router that you define that needs auth. This allows a non-authenticated user to find out which routes are defined and which ones are not.