Bird
Raised Fist0
Expressframework~10 mins

Mounting routers with app.use in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mounting routers with app.use
Create Express app
↓
Create Router
↓
Define routes on Router
↓
Mount Router on app with app.use(path, router)
↓
Incoming request to app
↓
Check if request URL matches mount path
Yes↓
Pass request to Router
↓
Router handles route
↓
Send response
↓
Request complete
This flow shows how an Express app creates a router, mounts it with app.use, and how requests matching the mount path are handled by the router.
Execution Sample
Express
const express = require('express');
const app = express();
const router = express.Router();
router.get('/hello', (req, res) => res.send('Hello from router'));
app.use('/api', router);
This code creates an Express app, a router with a /hello route, and mounts the router at /api.
Execution Table
StepActionRequest URLMatch Mount Path?Router Route Matched?Response Sent
1Request arrives at app/api/helloYes (/api)Yes (/hello)Hello from router
2Request arrives at app/api/goodbyeYes (/api)No404 Not Found
3Request arrives at app/helloNoN/A404 Not Found
💡 Requests not matching the mount path or router routes result in 404 responses.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
appExpress app instanceReceives /api/helloReceives /api/goodbyeReceives /hello
routerExpress router instanceHandles /hello routeNo matching routeNo matching route
request URLN/A/api/hello/api/goodbye/hello
responseN/ASent 'Hello from router'Sent 404Sent 404
Key Moments - 2 Insights
Why does a request to /hello not get handled by the router mounted at /api?
Because the router is mounted at /api, only requests starting with /api match the mount path (see execution_table row 3). Requests to /hello do not match and are not passed to the router.
What happens if the router does not have a route matching the request after matching the mount path?
If the router has no matching route (see execution_table row 2), Express returns a 404 Not Found response because no handler was found.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response is sent when the request URL is /api/hello?
A"Hello from router"
B404 Not Found
CNo response sent
D"Hello from app"
💡 Hint
Check execution_table row 1 under 'Response Sent'
At which step does the request URL not match the mount path?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at 'Match Mount Path?' column in execution_table
If the router was mounted at '/' instead of '/api', what would happen to the request at step 3?
AIt would be handled by the router if a matching route exists
BIt would still return 404 immediately
CThe app would crash
DThe request would be ignored
💡 Hint
Consider how mounting at '/' matches all paths, see concept_flow
Concept Snapshot
Mount routers with app.use(path, router)
- Create router with express.Router()
- Define routes on router
- Mount router on app with app.use('/path', router)
- Requests starting with '/path' go to router
- Router handles routes relative to mount path
- Non-matching requests skip router
Full Transcript
This lesson shows how to mount routers in Express using app.use. First, you create an Express app and a router. Then you define routes on the router. Next, you mount the router on the app at a specific path using app.use. When a request comes in, Express checks if the URL starts with the mount path. If yes, it passes the request to the router. The router then tries to match the rest of the URL to its routes. If a route matches, it handles the request and sends a response. If no route matches, Express sends a 404 Not Found. Requests that do not start with the mount path do not reach the router and also get 404 if no other handler exists. This way, routers help organize routes under specific URL prefixes.

Practice

(1/5)
1. What is the main purpose of using app.use to mount routers in Express?
easy
A. To automatically generate HTML pages
B. To directly send responses without defining routes
C. To group related routes under a common base path for better organization
D. To replace the Express app with a router

Solution

  1. Step 1: Understand what app.use does

    app.use mounts middleware or routers at a specified path, grouping routes.
  2. Step 2: Identify the benefit of mounting routers

    Mounting routers organizes routes under a base path, making code cleaner and easier to maintain.
  3. Final Answer:

    To group related routes under a common base path for better organization -> Option C
  4. Quick Check:

    Mount routers = group routes [OK]
Hint: Mount routers to group routes under one path [OK]
Common Mistakes:
  • Thinking app.use replaces the app
  • Believing it sends responses directly
  • Confusing mounting with automatic page generation
2. Which of the following is the correct syntax to mount a router named userRouter on the path /users using app.use?
easy
A. app.use('/users', userRouter);
B. app.use(userRouter, '/users');
C. app.get('/users', userRouter);
D. app.mount('/users', userRouter);

Solution

  1. Step 1: Recall the app.use syntax

    The correct syntax is app.use(path, router) to mount a router at a path.
  2. Step 2: Match the correct order and method

    app.use('/users', userRouter); uses app.use('/users', userRouter); which is correct. Others have wrong order or method.
  3. Final Answer:

    app.use('/users', userRouter); -> Option A
  4. Quick Check:

    app.use(path, router) = correct syntax [OK]
Hint: Remember: app.use(path, router) mounts router [OK]
Common Mistakes:
  • Swapping router and path order
  • Using app.get instead of app.use
  • Using non-existent app.mount method
3. Given the following code, what URL path will respond with 'User list'?
const express = require('express');
const app = express();
const userRouter = express.Router();

userRouter.get('/', (req, res) => res.send('User list'));

app.use('/users', userRouter);
medium
A. /users/
B. /
C. /user/
D. /users/list

Solution

  1. Step 1: Understand router path and mounting

    The router defines a GET route at '/' which is relative to where it is mounted.
  2. Step 2: Combine mount path and router route

    Since userRouter is mounted at '/users', the full path is '/users/' to reach the route.
  3. Final Answer:

    /users/ -> Option A
  4. Quick Check:

    Mount path + router route = full URL [OK]
Hint: Router path '/' + mount '/users' = '/users/' [OK]
Common Mistakes:
  • Ignoring mount path and using '/' alone
  • Confusing '/user/' with '/users/'
  • Assuming '/users/list' without route defined
4. What is wrong with this code snippet?
const express = require('express');
const app = express();
const router = express.Router();

router.get('/info', (req, res) => res.send('Info page'));

app.use(router, '/info');
medium
A. Missing app.listen call
B. Router cannot have routes with '/info' path
C. app.use cannot mount routers
D. The arguments to app.use are in the wrong order

Solution

  1. Step 1: Check app.use argument order

    The correct order is app.use(path, router), but here it is reversed.
  2. Step 2: Identify the error cause

    Passing router first and path second causes Express to treat router as middleware without a path, leading to unexpected behavior.
  3. Final Answer:

    The arguments to app.use are in the wrong order -> Option D
  4. Quick Check:

    app.use(path, router) order matters [OK]
Hint: app.use(path, router) order is strict [OK]
Common Mistakes:
  • Swapping router and path in app.use
  • Thinking router paths can't have '/info'
  • Ignoring missing app.listen (not related here)
5. You want to mount two routers, adminRouter and userRouter, so that /admin/dashboard and /users/profile work correctly. Which code correctly mounts both routers?
hard
A. app.use(adminRouter, '/admin');\napp.use(userRouter, '/users');
B. app.use('/admin', adminRouter);\napp.use('/users', userRouter);
C. app.use('/admin/dashboard', adminRouter);\napp.use('/users/profile', userRouter);
D. app.get('/admin', adminRouter);\napp.get('/users', userRouter);

Solution

  1. Step 1: Understand mounting routers at base paths

    Mount routers at base paths like '/admin' and '/users' so their internal routes append correctly.
  2. Step 2: Check each option for correct syntax and paths

    app.use('/admin', adminRouter);\napp.use('/users', userRouter); uses app.use('/admin', adminRouter); and app.use('/users', userRouter);, which is correct. app.use(adminRouter, '/admin');\napp.use(userRouter, '/users'); swaps arguments, C mounts at full paths (not base), D uses app.get which is incorrect for mounting routers.
  3. Final Answer:

    app.use('/admin', adminRouter); app.use('/users', userRouter); -> Option B
  4. Quick Check:

    Mount routers at base paths with app.use(path, router) [OK]
Hint: Mount routers at base paths with app.use(path, router) [OK]
Common Mistakes:
  • Swapping router and path in app.use
  • Mounting routers at full nested paths
  • Using app.get instead of app.use for routers
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