• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

46
Views
How can I use my verifyToken middleware in express router modules?

I have an express app like so:

// index.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');

app.use('/user', userRoutes);

const verifyToken = (req, res, next) => {
    // validate req.cookies.token
    next();
}

And I'm using an express router module like this:

// routes/userRoutes.js
const express = require('express');
const router = express.Router();

router.get('/:userid/data', verifyToken, async (req, res) => {
    const data = await db.query()
    res.json(data)
   
});

Obviously this doesn't work because verifyToken is not accesible within the module. How can I use the same verifyToken middleware function throughout different express modules?

about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

Move verifyToken to a different file and export it from there.

Then you can import it in other places.

One thing that you can do, that works well is to group all your authed routes under a common path and use router.use to make sure that you apply the verifyToken middleware on all of them.

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.