Bird
Raised Fist0
Expressframework~10 mins

Separating routes into files in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Separating routes into files
Create main app file
↓
Create route file
↓
Export router from route file
↓
Import router in main app
↓
Use router with app.use()
↓
Start server and handle requests
This flow shows how to split routes into separate files, export them, and use them in the main Express app.
Execution Sample
Express
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
app.listen(3000);
Main app imports user routes from a separate file and uses them under '/users' path.
Execution Table
StepActionFileResult
1Create main app file with express appapp.jsExpress app instance created
2Create route file with express.Router()routes/users.jsRouter instance created with routes
3Export router from route fileroutes/users.jsRouter exported
4Import router in main appapp.jsRouter imported as userRoutes
5Use router with app.use('/users', userRoutes)app.jsRoutes under '/users' path registered
6Start server with app.listen(3000)app.jsServer listening on port 3000
7Request to '/users/profile'app.js + routes/users.jsRouter handles request and sends response
8Request to '/users/settings'app.js + routes/users.jsRouter handles request and sends response
9Request to '/other'app.jsNo matching route, 404 or default response
💡 Server runs indefinitely until stopped; requests handled by registered routers.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5Final
appundefinedExpress app instanceExpress app instanceExpress app with userRoutes registeredRunning server
userRoutesundefinedRouter instanceRouter instanceRouter instanceRouter used for '/users' routes
Key Moments - 3 Insights
Why do we use express.Router() in a separate file instead of app directly?
Using express.Router() lets us group related routes in one file and export them. This keeps code organized. See execution_table step 2 and 3 where router is created and exported.
What does app.use('/users', userRoutes) do exactly?
It tells Express to use all routes defined in userRoutes under the '/users' path prefix. So '/users/profile' calls the profile route inside userRoutes. See execution_table step 5.
What happens if a request does not match any route?
Express returns a 404 or default response because no route handled the request. See execution_table step 9 where '/other' has no matching route.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result after step 3?
ARouter imported in main app
BRouter exported from route file
CServer started and listening
DRoutes registered under '/users'
💡 Hint
Check the 'Result' column for step 3 in the execution_table.
At which step does the main app start listening for requests?
AStep 5
BStep 4
CStep 6
DStep 2
💡 Hint
Look for 'Server listening on port 3000' in the execution_table.
If we change app.use('/users', userRoutes) to app.use('/api', userRoutes), what changes in the execution?
ARoutes will be under '/api' instead of '/users'
BRouter will not be imported
CServer will not start
DNo routes will work
💡 Hint
Refer to step 5 in execution_table where the path prefix is set.
Concept Snapshot
Separate routes into files using express.Router().
Export router from route file.
Import router in main app.
Use app.use('/path', router) to mount routes.
Keeps code organized and modular.
Server handles requests via mounted routers.
Full Transcript
This lesson shows how to organize Express routes by separating them into different files. First, you create a main app file that initializes the Express app. Then, you create a route file where you use express.Router() to define related routes. You export this router from the route file. In the main app file, you import the router and use app.use() to mount it under a specific path prefix like '/users'. This way, requests to '/users/profile' or '/users/settings' are handled by the routes defined in the separate file. The server listens on a port and handles requests accordingly. This approach keeps your code clean and easier to maintain.

Practice

(1/5)
1. What is the main benefit of separating routes into different files in an Express app?
easy
A. It makes the app run faster.
B. It keeps the app organized and easier to maintain.
C. It automatically secures the routes.
D. It removes the need for middleware.

Solution

  1. Step 1: Understand code organization

    Separating routes into files helps keep code clean and manageable as the app grows.
  2. Step 2: Identify benefits

    This separation does not affect speed or security directly but improves maintainability.
  3. Final Answer:

    It keeps the app organized and easier to maintain. -> Option B
  4. Quick Check:

    Organized code = easier maintenance [OK]
Hint: Think about code clarity and maintenance benefits [OK]
Common Mistakes:
  • Confusing organization with performance improvements
  • Assuming route separation adds security automatically
  • Thinking middleware is not needed after separation
2. Which of the following is the correct way to create a router in a separate file named users.js?
easy
A. const router = express.Router(); module.exports = router;
B. const router = new express.Router(); export default router;
C. const router = express.Router; module.exports = router();
D. const router = express.Router(); export router;

Solution

  1. Step 1: Create router instance correctly

    Use express.Router() to create a new router instance.
  2. Step 2: Export the router properly

    Use module.exports = router; to export it for use in other files.
  3. Final Answer:

    const router = express.Router(); module.exports = router; -> Option A
  4. Quick Check:

    Correct router creation and export = const router = express.Router(); module.exports = router; [OK]
Hint: Remember to call Router() and use module.exports [OK]
Common Mistakes:
  • Forgetting parentheses after Router
  • Mixing CommonJS and ES module syntax
  • Exporting router incorrectly
3. Given the following code in users.js:
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => {
  res.send('User Profile');
});
module.exports = router;
And in app.js:
const express = require('express');
const app = express();
const usersRouter = require('./users');
app.use('/users', usersRouter);
app.listen(3000);
What will be the response when a client requests /users/profile?
medium
A. User Profile
B. Cannot GET /users/profile
C. 404 Not Found error
D. Server crashes with error

Solution

  1. Step 1: Understand route prefixing

    The router is mounted at /users, so /profile inside router becomes /users/profile.
  2. Step 2: Check route handler response

    The route /profile sends 'User Profile' as response.
  3. Final Answer:

    User Profile -> Option A
  4. Quick Check:

    Route prefix + handler response = 'User Profile' [OK]
Hint: Remember mounted path prefixes router routes [OK]
Common Mistakes:
  • Forgetting the prefix from app.use
  • Expecting route at root instead of prefixed path
  • Assuming 404 without checking router setup
4. You have this code in products.js:
const express = require('express');
const router = express.Router();
router.get('/list', (req, res) => {
  res.send('Product List');
});
// Missing module.exports here
And in app.js:
const express = require('express');
const app = express();
const productsRouter = require('./products');
app.use('/products', productsRouter);
app.listen(3000);
What error will occur when starting the app or accessing /products/list?
medium
A. SyntaxError due to missing export
B. TypeError: Cannot read property 'use' of undefined
C. No error, but route won't respond
D. productsRouter is undefined, causing an error

Solution

  1. Step 1: Check module export in products.js

    Since module.exports is missing, require('./products') returns undefined.
  2. Step 2: Understand impact in app.js

    Using undefined as router in app.use causes an error when app tries to use it.
  3. Final Answer:

    productsRouter is undefined, causing an error -> Option D
  4. Quick Check:

    Missing export = undefined import error [OK]
Hint: Always export router to avoid undefined imports [OK]
Common Mistakes:
  • Assuming app runs without export
  • Confusing syntax error with runtime error
  • Not checking module.exports presence
5. You want to separate routes for /api/users and /api/products into two files: users.js and products.js. Each file exports a router with routes starting at /. How should you mount these routers in app.js to correctly handle requests to /api/users/profile and /api/products/list?
hard
A. app.use('/api', usersRouter); app.use('/api', productsRouter);
B. app.use('/users', usersRouter); app.use('/products', productsRouter);
C. app.use('/api/users', usersRouter); app.use('/api/products', productsRouter);
D. app.use('/', usersRouter); app.use('/', productsRouter);

Solution

  1. Step 1: Understand router base paths

    Each router handles routes starting at /, so mounting them at specific paths adds prefixes.
  2. Step 2: Mount routers with full API paths

    Mount usersRouter at /api/users and productsRouter at /api/products to match desired URLs.
  3. Final Answer:

    app.use('/api/users', usersRouter); app.use('/api/products', productsRouter); -> Option C
  4. Quick Check:

    Mount routers at full paths for correct URL handling [OK]
Hint: Mount routers at full URL prefixes to match routes [OK]
Common Mistakes:
  • Mounting routers at wrong or incomplete paths
  • Mounting both routers at same path causing conflicts
  • Assuming routers handle full paths internally
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard