Hi everyone,
Is there better way to have protected routes, in expressjs, I'm sensing some code messy while code expands while i'v to repeat the middleware to all the routes.
Any better way to initialize like in Laravel group routes. My code below.
router.post("/create", controller.authController.isAuthenticated, controller.articleController.create)
router.get("/edit/:id", controller.authController.isAuthenticated, controller.articleController.edit)
router.put("/update/:id", controller.authController.isAuthenticated, controller.articleController.update)
router.delete("/delete/:id", controller.authController.isAuthenticated, controller.articleController.delete)
Imran Khan
Check out Inversify and the supplemental utility library inversify-express-utils. You'll have to use TypeScript, but it leads to very clean application code for Express. You can add middleware for an entire controller, and as an added bonus, you now have dependency injection. Example:
@controller('/article', authenticator)
export class ArticleController {
@httpGet('/')
get(req, res) {
res.status(404);
}
}
Abinav Seelan
UI Engineer @Flipkart β’ https://abinavseelan.com π
If you know what your protected and unprotected routes are you could order your middleware stack as follows π
// all unprotected routes app.use(controller.authController.isAuthenticated); // all protected routesHere, only the protected routes will have the request go through the
isAuthenticatedcheck before triggering the specific route, since the middleware are executed top to bottom.I'm not sure what the actually solution to this is tbh. This is just something off the top of my head. π