I’m working on a Node.js/Express application, and as the project grows, I’m starting to run into issues with managing and registering routes in a centralized app.js file. Here’s how I’ve structured my project so far:
- I have an app/ folder with subfolders for different modules, such as
auth, cart, shop, and admin. - Inside each module, I have files like routes, controllers, services,
repositories, etc. - In the app.js file (which is centralized), I register all the module
routes using app.use()
Problem: This setup works fine when the app is small, but as more routes and modules are added, registering all routes in app.js is becoming harder to maintain. The file is getting cluttered, and I feel it’s not the best practice as the app scales.
Question What’s the best way to organize and manage route registration in a growing Node.js/Express application? Should I consider dynamically loading routes or implementing some sort of route centralization strategy to keep app.js clean and maintainable? Any recommendations or best practices for structuring routes in larger Express apps?
app.js
const express = require('express');
const app = express();
const connectDB = require('./config/database');
const authRoutes = require('./app/auth/routes/authRoutes');
app.use(express.json());
connectDB();
app.use('/api/authenticate', authRoutes);
module.exports = app;
index.js
require('dotenv').config();
const config = require('./config/envConfig');
const logger = require('./utils/logger');
const app = require('./app');
const PORT = config.port || 5000;
app.get('/', (req, res) => res.status(200).send('HELLO WORLD!'));
// Error Handling
app.use((err, req, res, next) => {
logger.error(`Error: ${err.message}`);
res.status(500).json({ message: 'Internal Server Error', error: err.message });
});
app.all('*', (req, res) => res.status(404).json({ message: 'No Matching Route' }));
// Start the server
app.listen(PORT, (err) => {
if (err) {
logger.error(`Error starting server: ${err.message}`);
process.exit(1); // Exit the process if the server fails to start
}
logger.info(`Server running on port ${PORT}`);
});