MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
MVC Architecture: Splitting Routes, Controllers & Service Layers0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
4.1Middleware Pipeline: Application-Level, Router-Level & Third-Party4.2RESTful API Design Standards: HTTP Verbs, Status Codes & Idempotency4.3MVC Architecture: Splitting Routes, Controllers & Service Layers4.4Global Error Handling Middleware & Custom AppError Classes
HomeTutorialsNode.js & Express.jsMVC Architecture: Splitting Routes, Controllers & Service Layers
Global Error Handling Middleware & Custom AppError Classes

MVC Architecture: Splitting Routes, Controllers & Service Layers

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

In beginner tutorials, developers often stuff database queries, business logic, validation, and responses into a single massive app.get() callback. In production enterprise applications, this leads to an unmaintainable "spaghetti codebase". Professional Node.js engineering adopts the MVC (Model-View-Controller) / Service-Layer Architecture.


1. The Separation of Concerns Pattern

  1. 1
    Routes (routes/): Define endpoints, match HTTP verbs, and apply route-specific middleware (guards). No business logic.
  2. 2
    Controllers (controllers/): Parse HTTP inputs (req.body, req.params), call the appropriate service methods, and format the HTTP response.
  3. 3
    Services (services/): Pure business logic (tax calculations, calling third-party APIs, orchestrating multi-step workflows). Independent of Express req/res.
  4. 4
    Models (models/): Database schemas, queries, and data persistence contracts (Mongoose, Prisma, TypeORM).

Visual Architecture & Process Flow

How data and code flow step-by-step

Flowchart
Step 1
HTTP Request -
Step 2
Route -
Step 3
Controller -
Step 4
Service -
Step 5
Model
Database

2. Real-World Implementation

1. The Route: src/routes/product.routes.js

1import { Router } from 'express';
2import * as productController from '../controllers/product.controller.js';
3import { requireAuth } from '../middleware/auth.middleware.js';
4 
5const router = Router();
6 
7router.get('/', productController.getAllProducts);
8router.get('/:id', productController.getProductById);
9router.post('/', requireAuth, productController.createProduct);
10 
11export default router;

2. The Controller: src/controllers/product.controller.js

1import * as productService from '../services/product.service.js';
2 
3export async function getAllProducts(req, res, next) {
4 try {
5 const { category, page } = req.query;
6 const products = await productService.getFilteredProducts({ category, page });
7 res.status(200).json({ status: 'success', data: products });
8 } catch (error) {
9 next(error); // Forward to global error handler
10 }
11}
12 
13export async function createProduct(req, res, next) {
14 try {
15 const product = await productService.createNewProduct(req.body, req.user.id);
16 res.status(201).json({ status: 'success', data: product });
17 } catch (error) {
18 next(error);
19 }
20}

3. The Service: src/services/product.service.js

1import Product from '../models/product.model.js';
2 
3export async function createNewProduct(payload, creatorId) {
4 // Business logic: enforce SKU uniqueness, check category limits
5 const existing = await Product.findOne({ sku: payload.sku });
6 if (existing) {
7 const err = new Error('A product with this SKU already exists');
8 err.statusCode = 409;
9 throw err;
10 }
11 
12 return await Product.create({ ...payload, createdBy: creatorId });
13}

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the primary responsibility of a Controller in an Express MVC architecture?
Question 2
Why should business logic and database queries NOT be placed directly inside Express route definition files?
Question 3
In the 3-tier architecture (Route -> Controller -> Service), what does the Service layer interact with?
Question 4
How should an error occurring inside a controller be passed to the centralized error-handling middleware?
Question 5
What is the benefit of keeping Service functions free of req and res objects?

Next Lesson

Global Error Handling Middleware & Custom AppError Classes

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
RESTful API Design Standards: HTTP Verbs, Status Codes & IdempotencyGlobal Error Handling Middleware & Custom AppError Classes

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext