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.

Project folder structure for a scalable Express API โ€” Building Your First API with Node.js and Express โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley