MVC Architecture Example with Node.js
When working on real-world Node.js projects, it's important to organize your code properly. One of the most common and effective patterns for doing this is the MVC Architecture.
What is MVC?
MVC stands for:
- M – Model (Handles the data)
- V – View (Handles the UI)
- C – Controller (Handles the logic and routes)
MVC Flow Summary
Here's how everything connects:
User ➝ Controller ➝ Model ➝ View ➝ User
- The User interacts with the app.
- The Controller receives the request and communicates with the Model.
- The Model processes data and sends it back.
- The View displays the result to the user.
File Structure in MVC
Create the following folders in your project:
project/
├── controllers/
│ └── usersController.js
├── models/
│ └── usersModel.js
├── views/
│ └── users.ejs
├── index.js
Step-by-Step Setup
Create Basic Express App
In index.js
:
import express from "express";
import { handleUsers } from "./controllers/usersController.js";
const app = express();
app.set("view engine", "ejs");
// Route
app.get("/user", handleUsers);
app.listen(3200, () => {
console.log("Server is running on port 3200");
});
Create Controller – controllers/usersController.js
The controller connects the model and view.
import { userList } from "../models/usersModel.js";
export function handleUsers(req, resp) {
const usersData = userList(); // Get data from model
resp.render("users", { users: usersData }); // Send data to view
}
Create Model – models/usersModel.js
export function userList() {
return ["Anil", "Sidhu", "Sam", "Peter", "Bruce"];
}
Create View – views/users.ejs
This is what the user sees on the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users List</title>
</head>
<body>
<h1>User List Page</h1>
<ul>
<% for (let i = 0; i < users.length; i++) { %>
<li><%= users[i] %></li>
<% } %>
</ul>
</body>
</html>
We loop through the users array and display each user in a list.