Peter Orosz Peter Orosz - 4 months ago 11
Node.js Question

Express - export multiple Router()s or a single Router()?

I'm new to Express and programming in general.

If you follow this book you learn to create a single Router() which maps all the routes to all the controllers. You end up having:

controllers
users.js
(other controllers....)
routes
routes.js


This router is then introduced to your app via a single call to
app.use(router)
.




However, if you generate your app via
express-generator
, it will generate a sample structure with multiple
Router()
s, which are then mounted to your app via multiple
app.use()
calls. For example:

app.use('/users', users) // mounts a Router()
app.use('/posts', posts) // mounts another Router()



It seems that Express prefers to have a seperate Router mounted for each controller. Have I got it right?


In the
express-generator
example, callbacks are hard-wired into routes. Let's say you want to introduce controllers into your code.

You would end up having something like this?

controllers
users
routes.js
callbacks.js
[other controller]
[its Router()].js
[its callbacks].js


My questions is, which is the better way to go?

Is there some architectural concept I misunderstand? (Maybe I should be hard-wiring callbacks into routes when I'm usign multiple Routers?)

Thank you for all the answers.

Answer

Multi-routers allows to separate your routes in modules. It avoids to have a big file with all routes. For example, if you take app.use('/users', users), your users.js file will contain all routes associated to users.

Personally, I work on a project with mongoose (http://mongoosejs.com/) which use this architecture :

express/
    index.js <- Main file to configure express router with adding middlewares, etc.
    routes.js <- All your routes are required in this file 
    entities/
        users/
            users.model.js <- Model of the user
            users.controller.js <- Controller associated to the model. Any route call a function of the controller
            users.routes.js <- All routes for users
        projects/
            projects.model.js
            projects.controller.js
            projects.routes.js

With a multi-routers architecture, you will gain scalability and readability. And separation between callbacks and routes avoid to pollute your router with controllers code.

Comments