user1354934 user1354934 - 4 months ago 8
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

app.js
.

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
routes/index.js
, and I want to use this
authenticate()
, how can I set that up in my
app.js
?

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
authenticate()
?

Thanks

Answer

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);
initializeRoutes(app);
Comments