Breaking Out Routes

When working on large ExpressJS projects, often times it makes sense to break out routes into their own files to keep better track of things and keep the project organized, clean and concise. There are several ways to do this and it seems like everyone does it differently. In this short post i’ll outline my preferred method of organizing routes into their own files with a simple and easy to maintain structure.

The first step is to make the index.js file that will be the root of the server for the pseudo project

index.js
1
2
3
4
5
6
7
8
9
10
11
// Import Express, Express App
const express = require('express');
const app = express();

// Require All Routes
app.use('/', require('./Routes'));

// Start Server
app.listen(3001, () => {
console.log(`Running at http://localhost:3001 !`);
});

Now we need a ./Routes directory, so create Routes in the root of your project and the file Routes/index.js that will automatically load all our routes when it’s called from the main index.js file. Now let’s create Routes/index.js

Routes/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
// Get the Express Router
const router = require('express').Router();

// Import User related routes from Routes/User.js
// All routes in the file will be mounted at {root}/user/{route}
router.use('/user', require('./User'));

// Import Test related routes from Routes/Test.js
// All routes in the file will be mounted at {root}/test/{route}
router.use('/test', require('./Test'));

// Export the Router with all our routes attached
module.exports = router;

Now we need the routes files, for simplicity i’ll just outline one file (Routes/User.js), it’s the same for each routes file that is auto loaded from Routes/index.js

Routes/User.js
1
2
3
4
5
6
7
8
9
10
11
// Get the Express Router
const router = require('express').Router();

router.get( ... )

router.post( ... )

// etc.

// Export the Router with all our User related routes attached
module.exports = router;

Now one good thing that this introduces is the ability to apply a middleware to an entire group of routes at once, for example if we had a bunch of protected routes that require a user to be logged in to access we could just add this to the Routes/index.js file

Routes/index.js
1
2
3
4
5
6
7
8
9
// Your middleware function to check if the user is logged in
// this is just a simple example
const { loggedIn } = require('./Middlewares');

// Putting the middleware here makes every route in the
// Routes/Protected.js file use the middleware automatically.
// So you don't need to apply the middleware to each
// individual route
router.use('/protected', loggedIn, require('./Protected'));