craft
craft

Reputation: 2135

Why and when should I use express.Router()?

Question 1: Why should I use express.Router()?

The documentation says routers are good for:

Cannot, however, seem to find any other reasons to move these routes into smaller router units. Wondering if there's a performance reason or something else I'm not considering here.

Question 2: When should I use express.Router() ?

For example, I have about 10 routes for an express app, and the routes can certainly be categorized into different routers (widgets, users, etc).

Does it make sense to use express.Router() in this app? Trying to gauge if express.Router is used for much bigger projects, where there are dozens (and dozens) of routes. With 10 routes, it still feels somewhat manageable without breaking into separate routers.

Upvotes: 10

Views: 4491

Answers (2)

Usman Mutawakil
Usman Mutawakil

Reputation: 5259

I would use it. The labor cost on your end is minimal and its much cleaner to look at from your own perspective. 10 routes is sufficient to justify separation of concerns. I would do this even if I had a single route, so that when I look at my app.js or main app file, I'm only looking at code that effects the entire system.

Code Size Relevance

The size of the application doesn't matter. Its about not packing unrelated code together. From what you've articulated you have URLs like the list below all being routed from the same file.

  • /accounts
  • /users
  • /invoices
  • /sales
  • /products
  • /shoes
  • /monsters
  • /magic

Thats only 8, now what if you decide to add subdirectories? Having everything packed into one file will make you more likely to cut corners or avoid refactoring and looking at how unrelated the objects above are, do they really all belong in the same file?

Main.js

app.use('/accounts',accountsRoute)
app.use('/users',userRoute)
app.use('/invoices',invoicesRoute)
app.use('/dancers',dancersRoute)
app.use('/monsters',monstersRoute)
app.use('/magic',magicRoute)

Upvotes: 11

Paul
Paul

Reputation: 36329

It's mostly about code organization / maintainability and scoping middleware.

If all you have are ten routes, you're fine without it, especially if they all need the same middleware. At that size it's personal preference, there's no performance advantage or the like.

Once you start having 3-4 or more resources (models) and need routes for each to create,read, update and delete, or if some are authenticated and others are not, etc, you start appreciating the organization more.

Upvotes: 6

Related Questions