Search code examples
node.jsauthenticationexpresstokenjson-web-token

Specify per node route if authentication is needed or not


I m building a node web service. This contains multiple routes. Some of them need authentication, others not. I use json-web-token to create and verify tokens, that work, as long as I am happy with the following:

router
    // main routes
    .get('/', main.catchAll)
    .post('/register', main.register)
    .post('/authenticate', main.authenticate)
    .use(main.verifyToken)
    .get('/years', main.years)
    // game routes
    .get('/games', game.newestGames)
    .get('/game/title/:id', game.gameName)
    .get('/game/:id', game.gameDetails)
    .get('/genres', genres.genres)

This results in all routes that are defined after the .use(...) will need authentication. However, to keep track of all my routes I want to group them per category, but that means I am not able to use the verification as I am used to.

For example: I don't want the .get('/games', game.newestGames) to need authentication

Is there a way to specify per route that it needs verification or not?


Solution

  • Sure, you can either do:

    app.use('/years', main.varifyToken, main.years)
    

    Or if you want to make it only on some verbs:

    app.get('/years', main.years)
    app.post('/years', main.verifyToken, main.postYears)
    

    You can also look into using Routers to group functionality and auth. I find it easier to make sense of my routes when I do