Bird
Raised Fist0
Expressframework~10 mins

Route prefixing in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Route prefixing
Create Express app
↓
Create Router
↓
Define routes on Router
↓
Use Router with prefix
↓
App listens for requests
↓
Request comes in
↓
Check prefix match
Yes↓
Route handler runs
↓
Send response
↓
End
This flow shows how an Express app uses a router with a prefix to handle requests starting with that prefix.
Execution Sample
Express
const express = require('express');
const app = express();
const router = express.Router();
router.get('/hello', (req, res) => res.send('Hi'));
app.use('/api', router);
app.listen(3000);
This code creates a router with a '/hello' route, then prefixes it with '/api' in the main app.
Execution Table
StepActionRequest URLPrefix Match?Route MatchedResponse Sent
1App starts listening----
2Request received/api/helloYes/hello'Hi'
3Request received/helloNoNo route404 Not Found
4Request received/api/goodbyeYesNo route404 Not Found
5Request received/api/hello/worldYesNo route404 Not Found
💡 Requests stop processing when no matching route is found or response is sent.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5
request.url-/api/hello/hello/api/goodbye/api/hello/world
prefix '/api'setmatchednot matchedmatchedmatched
route matchednone/hellononenonenone
responsenone'Hi'404404404
Key Moments - 2 Insights
Why does '/hello' not match when prefix '/api' is used?
Because the router only handles routes starting with '/api'. The request '/hello' lacks this prefix, so it does not match any route in the router (see execution_table row 3).
What happens if the request URL has the prefix but no matching route?
The router checks the prefix and matches it, but since no route matches the rest of the path, it returns 404 Not Found (see execution_table rows 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what response is sent when the request URL is '/api/hello'?
A404 Not Found
B'Hi'
CNo response
DError
💡 Hint
Check row 2 in the execution_table under 'Response Sent'
At which step does the prefix '/api' not match the request URL?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Prefix Match?' column in execution_table
If we change the prefix to '/v1' instead of '/api', what happens to the response for request '/api/hello'?
AResponse is 404 Not Found
BResponse is an error
CResponse is 'Hi'
DResponse is empty
💡 Hint
Changing prefix means '/api/hello' no longer matches the router prefix, see variable_tracker for prefix matching
Concept Snapshot
Route Prefixing in Express:
- Create a router with routes (e.g., router.get('/hello'))
- Use app.use('/prefix', router) to add a prefix
- Requests must start with prefix to reach router routes
- Router matches routes after prefix
- Non-matching routes or prefixes result in 404
- Helps organize routes under common path
Full Transcript
Route prefixing in Express means you create a router with some routes, then tell the main app to use that router but only for URLs starting with a certain prefix. When a request comes in, Express checks if the URL starts with the prefix. If yes, it removes the prefix and tries to match the rest of the path to the router's routes. If a route matches, its handler runs and sends a response. If no route matches, Express sends a 404 Not Found. If the prefix does not match, the router is skipped. This helps organize routes under a common path segment, like '/api'.

Practice

(1/5)
1. What is the main purpose of route prefixing in Express?
easy
A. To encrypt route URLs for security
B. To speed up the server response time
C. To automatically generate HTML pages
D. To group routes under a shared path for better organization

Solution

  1. Step 1: Understand route prefixing concept

    Route prefixing means putting multiple routes under one common path prefix to keep code organized.
  2. Step 2: Identify the main benefit

    This grouping helps keep URLs clean and code easier to maintain by avoiding repetition of the same path.
  3. Final Answer:

    To group routes under a shared path for better organization -> Option D
  4. Quick Check:

    Route prefixing = Group routes under shared path [OK]
Hint: Route prefixing groups routes by shared path prefix [OK]
Common Mistakes:
  • Thinking it improves server speed
  • Confusing with automatic HTML generation
  • Assuming it encrypts URLs
2. Which of the following is the correct way to prefix routes using Express Router?
easy
A. app.use('/api', router);
B. router.prefix('/api');
C. app.route('/api').use(router);
D. router.attach('/api');

Solution

  1. Step 1: Recall Express Router usage

    Express uses app.use(prefix, router) to attach a router with a path prefix.
  2. Step 2: Check each option

    Only app.use('/api', router) is valid syntax; others are not Express methods.
  3. Final Answer:

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

    Prefix routes with app.use(prefix, router) [OK]
Hint: Use app.use('/prefix', router) to prefix routes [OK]
Common Mistakes:
  • Using non-existent router.prefix() method
  • Trying app.route() to prefix router
  • Using router.attach() which doesn't exist
3. Given this code, what URL path will respond with 'Hello World'?
const express = require('express');
const app = express();
const router = express.Router();

router.get('/hello', (req, res) => {
  res.send('Hello World');
});

app.use('/api', router);
medium
A. /hello
B. /api
C. /api/hello
D. /hello/api

Solution

  1. Step 1: Understand route prefixing effect

    The router defines '/hello', but it is attached to app with prefix '/api'.
  2. Step 2: Combine prefix and route path

    The full path becomes '/api' + '/hello' = '/api/hello'.
  3. Final Answer:

    /api/hello -> Option C
  4. Quick Check:

    Prefix + route path = full URL [OK]
Hint: Full route = prefix + router path [OK]
Common Mistakes:
  • Ignoring the prefix and choosing '/hello'
  • Choosing just the prefix '/api' without route
  • Reversing prefix and route order
4. Identify the error in this Express route prefixing code:
const express = require('express');
const app = express();
const router = express.Router();

router.get('/test', (req, res) => {
  res.send('Test route');
});

app.use(router, '/api');
medium
A. router.get path should not start with '/'
B. The order of arguments in app.use is incorrect
C. router must be created with express.Route() not express.Router()
D. res.send should be res.json for route prefixing

Solution

  1. Step 1: Check app.use argument order

    app.use expects (path, router), but code uses (router, path) which is wrong.
  2. Step 2: Confirm other parts are correct

    router.get with '/test' is valid; express.Router() is correct; res.send works fine.
  3. Final Answer:

    The order of arguments in app.use is incorrect -> Option B
  4. Quick Check:

    app.use(path, router) order matters [OK]
Hint: app.use(path, router) not app.use(router, path) [OK]
Common Mistakes:
  • Swapping arguments in app.use
  • Thinking router path can't start with '/'
  • Confusing express.Router() with express.Route()
5. You want to create two routers: one for '/users' and one for '/products'. How do you correctly prefix and mount them in Express?
hard
A. app.use('/users', usersRouter); app.use('/products', productsRouter);
B. usersRouter.use('/users'); productsRouter.use('/products'); app.use(usersRouter); app.use(productsRouter);
C. app.route('/users').use(usersRouter); app.route('/products').use(productsRouter);
D. app.use(usersRouter, '/users'); app.use(productsRouter, '/products');

Solution

  1. Step 1: Understand correct mounting syntax

    To prefix routers, use app.use(prefix, router) for each router separately.
  2. Step 2: Evaluate options

    app.use('/users', usersRouter); app.use('/products', productsRouter); correctly uses app.use with prefix and router. Others misuse methods or argument order.
  3. Final Answer:

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

    Mount each router with app.use(prefix, router) [OK]
Hint: Mount each router with app.use('/prefix', router) [OK]
Common Mistakes:
  • Using router.use() without attaching to app
  • Using app.route() incorrectly for routers
  • Swapping arguments in app.use
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