Search code examples
expressjwtexpress-jwt

With Express-jwt, how to use routing aliases?


This is the Express way of wiring the routing:

// routes
app.get('/grid', function ..
..

app.use('/grid', expressJwt({secret : secret}));

But when I use aliases to wire the routing (express >= 4) ..

var gridRouter  = express.Router()
, authRouter  = express.Router();

// routes
grid.get('/', function ..

app.use('/grid', gridRouter)
app.use('/auth', authRouter)

... jwt does not work.


Solution

  • I found the answer myself and wanted to share it. We can't protect individual router aliases with ExpressJWT, yet we can protect the paths like we are used to.

    var gridRouter  = express.Router()
    , authRouter  = express.Router();
    
    app.use('/grid/nestedGridPath', expressJwt({secret: secret}))
    app.use('/auth/nestedAuthPath', expressJwt({secret: secret}))
    
    app.use('/grid', gridRouter)
    app.use('/auth', authRouter)
    

    Sources: https://www.npmjs.org/package/express-jwt

    Update:

    As an aside, in case you have problems in getting express-Jwt to work at all, you can still wire it directly, e.g.:

    app.delete('/grid/delete/:id', expressJwt({secret:secret}), myFunc);