Splitting Routes

Oct 18, 2022

Split Route files

index.js

Sometimes it can be useful to split our routes into multiple files for organizational purposes. For instance, we could place all of our user registration and login routes in routes/users.js to make them separate from our main routes.

To do so, you need to register the route file in app.js.

Example:

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);

Note that the app.use() method is what defines which URL endpoint that will be used by the router file.

With

app.use('/users', usersRouter)

this means that we will not make reference to “/users” when declaring our routes.

For example,

if the following route is in users.js:

router.get('/register', (req, res) => {
    res.render('register');
}

Then it would be accessed at “/users/register”, not just “/register”.