user1354934 user1354934 - 1 year ago 64
Node.js Question

How do I set up routes in my node + express app to pass an authenticate method?

I'm following the auth0 backend set up tutorial, and I'm wondering how I can set up my routes in a separate file instead of in


In the tutorial, they create

var authenticate = jwt({
secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
audience: process.env.AUTH0_CLIENT_ID

and then
app.use('/secured', authenticate);

If I want to set up my routes in some routes folder
, and I want to use this
, how can I set that up in my

I know I have to do something like
var routes = require('./routes/index.js');
, but how do I set up the
app.use( .. )
in this case so it uses


Answer Source

You can define a routes module in ./routes/index.js like this:

// ./routes/index.js

module.exports = function (app) {
   app.get('/secured', getSecuredController);

function getSecuredController (req, res) {
   res.send('/secured OK');

And in your main app.js file:

// ./app.js

var initializeRoutes = require('./routes');
var authenticate = jwt({..});

app.use('/secured', authenticate);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download