Building Your First API with Node.js and ExpressLesson 2.5
Project folder structure for a scalable Express API
MVC folder structure, routes folder, controllers folder, middleware folder, models folder, config folder, environment variables, dotenv
Scalable Express Project Structure
A flat index.js file becomes unworkable past a handful of routes. Use a separation-of-concerns structure from day one so the project can grow without refactoring.
Recommended Structure
my-api/
โโโ index.js # server entry point, app.listen
โโโ app.js # express setup, middleware, route mounting
โโโ .env # environment variables (never commit)
โโโ routes/
โ โโโ users.js # route definitions only
โโโ controllers/
โ โโโ userController.js # business logic
โโโ middleware/
โ โโโ auth.js # authentication middleware
โโโ models/
โ โโโ user.js # data schema / DB model
โโโ config/
โโโ db.js # database connectionController Pattern
// controllers/userController.js
exports.getUser = async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user);
} catch (err) {
next(err); // pass to error middleware
}
};
// routes/users.js
const { getUser } = require('../controllers/userController');
router.get('/:id', getUser);Keep routes thin โ they declare URLs and delegate to controllers. Keep controllers focused on one resource. Use dotenv to load .env variables: require('dotenv').config() at the top of index.js.
