Node.js  

MVC Architecture in Node.js (With Code Examples)

Introduction

MVC (Model-View-Controller) is a widely used architectural pattern that helps developers structure code into three separate components:

  • Model: Manages data and business logic.
  • View: Represents the UI.
  • Controller: Handles user input and interactions.

Node.js, being a flexible backend runtime, doesn't enforce MVC, but you can build an MVC-style app using Express.js (a popular Node.js framework).

Project Structure (MVC Style)

mvc-app/
├── controllers/
│   └── userController.js
├── models/
│   └── userModel.js
├── routes/
│   └── userRoutes.js
├── views/
│   └── userView.ejs
├── app.js
└── package.json

Step-by-Step Code Implementation

1. Initialize Project

mkdir mvc-app && cd mvc-app
npm init -y
npm install express ejs

2. Create app.js (Entry Point)

// app.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');

app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));

app.use('/users', userRoutes);

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

3. Model - userModel.js

// models/userModel.js
let users = [];

module.exports = {
  getAllUsers: () => users,
  addUser: (user) => users.push(user),
};

4. View - userView.ejs

Create views/userView.ejs

<!DOCTYPE html>
<html>
<head>
  <title>User List</title>
</head>
<body>
  <h1>Users</h1>
  <ul>
    <% users.forEach(user => { %>
      <li><%= user.name %> - <%= user.email %></li>
    <% }) %>
  </ul>

  <form method="POST" action="/users">
    <input name="name" placeholder="Name" required />
    <input name="email" placeholder="Email" required />
    <button type="submit">Add User</button>
  </form>
</body>
</html>

5. Controller - userController.js

// controllers/userController.js
const userModel = require('../models/userModel');

exports.showUsers = (req, res) => {
  const users = userModel.getAllUsers();
  res.render('userView', { users });
};

exports.createUser = (req, res) => {
  const { name, email } = req.body;
  userModel.addUser({ name, email });
  res.redirect('/users');
};

6. Routes - userRoutes.js

// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');

router.get('/', userController.showUsers);
router.post('/', userController.createUser);

module.exports = router;

Running the App

node app.js

Visit: http://localhost:3000/users

You can add users, and they will be displayed on the same page.

Advantages of Using MVC in Node.js

  • Separation of concerns
  • Easier testing and debugging
  • Cleaner and organized project structure
  • Scalable for large apps

Conclusion

The MVC pattern in Node.js using Express helps structure your app in a clean and maintainable way. While Node.js doesn't enforce architecture rules, adopting MVC leads to better code management, especially as your project grows.