Discover how a simple pattern can turn chaotic route code into clean, easy-to-manage controllers!
Why Controller pattern for route handlers in Express? - Purpose & Use Cases
Imagine building a web app where every route's code is written directly inside the route definitions. As your app grows, you have dozens of routes all mixed with logic, making it hard to find or fix bugs.
Writing all route logic inline leads to messy, tangled code. It's slow to update, easy to break, and hard for others to understand. You might repeat code and struggle to test parts separately.
The Controller pattern organizes route logic into separate controller files. Each controller handles specific tasks, keeping routes clean and code easy to manage, test, and reuse.
app.get('/users', (req, res) => { /* fetch users, handle errors, send response */ });app.get('/users', userController.listUsers);This pattern makes your app scalable and maintainable by separating concerns and simplifying route handlers.
In a blog app, you can have a PostController managing all post-related actions, so adding new features or fixing bugs in posts won't affect other parts of your app.
Inline route logic gets messy and hard to maintain.
Controller pattern separates logic from routes for clarity.
It improves code reuse, testing, and teamwork.
Practice
controller pattern in Express route handlers?Solution
Step 1: Understand the controller pattern concept
The controller pattern means moving the logic that handles requests out of the route definitions into separate functions or files.Step 2: Identify the benefit of separation
This separation improves code organization, making it easier to read and maintain.Final Answer:
To separate route logic from routing setup for better organization -> Option AQuick Check:
Controller pattern = separation of concerns [OK]
- Thinking controllers combine all routes in one file
- Believing controllers write database queries directly
- Confusing controllers with middleware avoidance
getUser in an Express route?Solution
Step 1: Understand how to pass controller functions
In Express, route handlers expect a function reference, not the result of calling the function.Step 2: Identify correct syntax
PassinggetUserwithout parentheses passes the function itself. Using parentheses calls it immediately, which is incorrect here.Final Answer:
router.get('/user', getUser); -> Option DQuick Check:
Pass function reference without () [OK]
- Calling the controller function immediately with ()
- Using arrow functions incorrectly wrapping the controller
- Returning the function instead of calling it
/hello?
const sayHello = (req, res) => {
res.send('Hello from controller!');
};
router.get('/hello', sayHello);Solution
Step 1: Analyze the controller function behavior
ThesayHellofunction sends a plain text response 'Hello from controller!' when called.Step 2: Check route setup correctness
The route usessayHellocorrectly as the handler for GET requests to '/hello'.Final Answer:
Hello from controller! -> Option AQuick Check:
Controller sends response text [OK]
- Forgetting to call res.send inside controller
- Passing controller incorrectly causing runtime error
- Misreading route path causing 404
const userController = {
getUser: (req, res) => {
res.json({ name: 'Alice' });
}
};
router.get('/user', userController.getUser());Solution
Step 1: Check how controller function is passed
The code callsuserController.getUser()immediately, which runs the function and passes its result, not the function itself.Step 2: Understand correct usage
Express expects a function reference as the route handler, so it should beuserController.getUserwithout parentheses.Final Answer:
Calling userController.getUser() immediately instead of passing function -> Option CQuick Check:
Pass function reference, not call it [OK]
- Calling controller function instead of passing it
- Confusing res.json and res.send (both valid here)
- Assuming route path naming causes error
getUser, createUser, and deleteUser. Which approach best follows the controller pattern for clean code?Solution
Step 1: Understand controller pattern best practice
Controllers group related route logic into separate files or modules to keep code organized and reusable.Step 2: Evaluate options for clean code
Defining all user-related functions in a dedicateduserController.jsfile and importing them into the router file follows the pattern well.Final Answer:
Define all user-related functions in a separate userController.js file and import them in the router file -> Option BQuick Check:
Separate logic into controller files [OK]
- Putting all logic in main app file making it messy
- Mixing routes and logic in one file without separation
- Using anonymous functions inline reduces reusability
Ready to prove it?
Pass the test and this pattern moves unknown
