Script Valley
REST API Development: Beginner to Production
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 connection

Controller 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.