arrow_back Back to Tickets

Ticket #0de99a

open

Problem

use class on routes and have dynamic way to select different category of routes instead of having a lot of different routes listed.

Creator

marcus

Priority

2

Project Name

zfrika

Strategy

Absolutely ✅ — you can and often should use a class with Express routes in Node.js. It helps you organize your logic cleanly, especially for larger apps. Let’s go through a few ways to do this 👇 🧩 1. Basic Example: Class + Route Here’s a small example where a class handles all user-related logic, and the routes simply call the class methods. // controllers/UserController.js class UserController { getAll(req, res) { res.send('List of all users'); } getById(req, res) { const { id } = req.params; res.send(`User ID: ${id}`); } create(req, res) { res.send('User created!'); } } module.exports = new UserController(); Then use it in your route file: // routes/users.js const express = require('express'); const router = express.Router(); const userController = require('../controllers/UserController'); router.get('/', userController.getAll); router.get('/:id', userController.getById); router.post('/', userController.create); module.exports = router; In your main app: // app.js const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); app.use('/users', usersRouter); app.listen(3000, () => console.log('Server running on port 3000'));

Ticket Information

Ticket ID: 69122929eea567b5770de99a
Date Initiated: 11/11/2025, 2:03:00 AM
Status: open
Created: 11/10/2025, 10:04:25 AM
Last Updated: 11/10/2025, 10:33:15 AM