Grouping routes in Express

Aris picture Aris · Aug 11, 2016 · Viewed 19.6k times · Source

We can group our routes like this in Laravel:

Route::group("admin", ["middleware" => ["isAdmin"]], function () {

     Route::get("/", "AdminController@index");
     Route::post("/post", ["middleware" => "csrf", "uses" => "AdminController@index");

});

Basically, all the routes defined in admin group gets the isAdmin middleware and group name automatically. For example, post endpoint listens to admin/post not /post

Is there any way to do the same thing with Express? It would be awesome because my Laravel routes used to be so clean, whereas my Express routes are a bit messy/duplicated.

This is my routes.js on Express at the moment.

app.get("/admin", [passportConfig.isAuthenticated, passportConfig.isAdmin], AdminController.index);
app.post("/admin", [passportConfig.isAuthenticated, passportConfig.isAdmin], AdminController.postIndex);

Thank you.

Answer

Melle picture Melle · Nov 21, 2018

Since express 4 you can define and compose routers

const app = require('express');
const adminRouter = app.Router();

adminRouter.use(isAdmin);
adminRouter.get('/', admin.index); /* will resolve to /admin */
adminRouter.post('/post', csrf, admin.index); /* will resolve to /admin/post */

app.use('/admin', adminRouter); 

Hope that helps!