You can restrict access to certain routes exclusively for pro users, and I'll demonstrate how to integrate this feature into the boilerplate.
We will restrict access to the todos' public APIs exclusively for paid users.
- Create a file name restrictedRoute.js in middleware folder and paste the following code.
JavaScript
Copyconst User = require('../models/User'); const { responseList } = require('../errors/responseList'); const restrictedRoute = async (req, res, next) => { try { const { api_key } = req.query; let user = await User.findOne({ api_key }).exec(); if (user.status === 'pro') { next(); } else { res.status(401).send(responseList('401')); } } catch (error) { res.status(400).send(responseList('400', error.message)); } }; module.exports = restrictedRoute;
- Navigate to the routes/publicRoutes.js file and import middleware. Apply this middleware to all the public routes, so only pro users can use these APIs of your app.
JavaScript
Copy// app/routes/todoRoutes.js const express = require('express'); const router = express.Router(); const publicController = require('../controllers/publicController'); const restrictedRoute = require('../middleware/restrictedRoute'); router.get('/', restrictedRoute, publicController.getAllTodos); router.get('/:todoId', restrictedRoute, publicController.getSingleTodo); router.post('/', restrictedRoute, restrictedRoute, publicController.addTodo); router.put('/', restrictedRoute, publicController.updateTodo); router.delete('/', restrictedRoute, publicController.deleteTodo); module.exports = router;
Now only pro users can access these public api endpoints.