Bird
Raised Fist0
Expressframework~10 mins

Creating an Express Router - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - Creating an Express Router
Import express
↓
Create router with express.Router()
↓
Define routes on router
↓
Export router
↓
Import router in main app
↓
Use router with app.use()
↓
Server listens for requests
This flow shows how to create a router, add routes, export it, then use it in the main app to handle requests.
Execution Sample
Express
const express = require('express');
const router = express.Router();

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

module.exports = router;
This code creates a router, adds a GET route for '/hello', and exports the router.
Execution Table
StepActionEvaluationResult
1Import expressexpress module loadedexpress object available
2Create router with express.Router()router = express.Router()router object created
3Define GET route '/hello'router.get('/hello', handler)Route added to router
4Export routermodule.exports = routerrouter ready to be imported
5Import router in main appconst router = require('./router')router object imported
6Use router with app.use('/api', router)app.use('/api', router)Router mounted at '/api'
7Server listensapp.listen(port)Server ready to accept requests
8Request to '/api/hello'Matches router GET '/hello'Response: 'Hello World' sent
9Request to '/hello'No match404 Not Found
10Request to '/api/goodbye'No match404 Not Found
💡 Execution stops after server handles requests or no matching route found.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6Final
expressundefinedexpress objectexpress objectexpress objectexpress objectexpress objectexpress object
routerundefinedrouter objectrouter with '/hello' routeexported routerimported routerrouter mounted on '/api'router handles '/hello' requests
appundefinedundefinedundefinedundefinedapp objectapp with router mountedapp listening for requests
Key Moments - 3 Insights
Why do we create a router instead of adding routes directly to the app?
Creating a router lets us group routes and keep code organized. The execution_table rows 2 and 3 show router creation and route addition separate from the main app.
What happens if we request '/hello' instead of '/api/hello' after mounting the router at '/api'?
The request to '/hello' does not match any route because the router is mounted at '/api'. See execution_table row 9 where '/hello' returns 404.
How does the router know to respond with 'Hello World'?
The router has a GET route for '/hello' defined in step 3. When a request matches, the handler sends 'Hello World' as in step 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of 'router' after step 3?
AUndefined
BRouter object without any routes
CRouter object with '/hello' route added
DRouter object exported
💡 Hint
Check the 'Result' column at step 3 in execution_table.
At which step does the server start listening for requests?
AStep 6
BStep 7
CStep 5
DStep 4
💡 Hint
Look for 'Server listens' action in execution_table.
If we change app.use('/api', router) to app.use('/', router), what happens to the request path for '/hello'?
AIt will match and respond with 'Hello World'
BIt will still return 404
CIt will cause an error
DIt will redirect to '/api/hello'
💡 Hint
Refer to execution_table rows 6 and 9 about router mounting and request matching.
Concept Snapshot
Create an Express router with express.Router().
Add routes to the router (e.g., router.get('/path', handler)).
Export the router module.
Import and mount the router in the main app with app.use('/prefix', router).
Requests to '/prefix/path' are handled by the router.
This keeps route code organized and modular.
Full Transcript
This lesson shows how to create an Express router to organize routes. First, we import express and create a router object. Then we add routes to this router, like a GET route for '/hello' that sends 'Hello World'. We export this router so it can be used elsewhere. In the main app, we import the router and mount it at a path prefix like '/api' using app.use. When the server listens and receives requests, requests to '/api/hello' match the router's route and respond with 'Hello World'. Requests outside the prefix or to undefined routes return 404. This modular approach helps keep code clean and manageable.

Practice

(1/5)
1. What is the main purpose of using express.Router() in an Express app?
easy
A. To handle database connections
B. To start the Express server
C. To create a modular set of routes that can be mounted separately
D. To serve static files

Solution

  1. Step 1: Understand what express.Router() does

    This function creates a new router object that can hold routes separately from the main app.
  2. Step 2: Identify the purpose of modular routes

    Modular routes help organize code by grouping related routes, making the app easier to maintain.
  3. Final Answer:

    To create a modular set of routes that can be mounted separately -> Option C
  4. Quick Check:

    Router = modular routes [OK]
Hint: Router organizes routes separately for cleaner code [OK]
Common Mistakes:
  • Thinking router starts the server
  • Confusing router with database handling
  • Assuming router serves static files
2. Which of the following is the correct way to create a new Express router?
easy
A. const router = express.Router();
B. const router = new express.Router();
C. const router = express.createRouter();
D. const router = Router();

Solution

  1. Step 1: Recall the Express Router creation syntax

    The correct method is calling Router() as a function on the express object.
  2. Step 2: Check each option for syntax correctness

    const router = express.Router(); uses express.Router() correctly. const router = new express.Router(); wrongly uses new. const router = express.createRouter(); uses a non-existent method. const router = Router(); calls Router() without express..
  3. Final Answer:

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

    Correct syntax = express.Router() [OK]
Hint: Use express.Router() without new keyword [OK]
Common Mistakes:
  • Using new keyword with Router
  • Calling a non-existent createRouter method
  • Calling Router without express prefix
3. Given this code snippet, what will be the output when a GET request is made to /api/users?
const express = require('express');
const app = express();
const router = express.Router();

router.get('/users', (req, res) => {
  res.send('User list');
});

app.use('/api', router);

app.listen(3000);
medium
A. Cannot GET /api/users
B. Error: router not defined
C. 404 Not Found
D. User list

Solution

  1. Step 1: Understand route mounting with app.use('/api', router)

    This mounts the router under the path /api, so routes inside router are prefixed with /api.
  2. Step 2: Check the router route /users

    The router handles GET requests to /users, so combined with the mount path, the full path is /api/users.
  3. Final Answer:

    User list -> Option D
  4. Quick Check:

    Mounted path + router path = /api/users [OK]
Hint: Router path combines with app.use prefix [OK]
Common Mistakes:
  • Forgetting the mount path prefix
  • Expecting route at root instead of /api
  • Assuming router not mounted
4. Identify the error in this Express router code:
const express = require('express');
const router = express.Router;

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

module.exports = router;
medium
A. Missing parentheses when creating router instance
B. Route path should be '/info/' with trailing slash
C. res.send should be res.json
D. module.exports should export an object, not router

Solution

  1. Step 1: Check router creation syntax

    The code uses express.Router without parentheses, so it assigns the function itself, not an instance.
  2. Step 2: Confirm correct router instantiation

    It should be express.Router() to create a router instance that supports route methods.
  3. Final Answer:

    Missing parentheses when creating router instance -> Option A
  4. Quick Check:

    Router needs () to create instance [OK]
Hint: Router must be called as a function with () [OK]
Common Mistakes:
  • Forgetting () after express.Router
  • Thinking trailing slash is required
  • Confusing res.send with res.json
5. You want to create two routers: one for /users and one for /products. How do you correctly mount them in your Express app so that requests to /users/list and /products/list work as expected?
hard
A. app.use(usersRouter); app.use(productsRouter);
B. app.use('/users', usersRouter); app.use('/products', productsRouter);
C. app.use('/list', usersRouter); app.use('/list', productsRouter);
D. app.get('/users', usersRouter); app.get('/products', productsRouter);

Solution

  1. Step 1: Understand router mounting with path prefixes

    To handle routes under /users and /products, mount each router with those paths using app.use().
  2. Step 2: Check each option for correct usage

    app.use('/users', usersRouter); app.use('/products', productsRouter); mounts routers correctly with prefixes. app.use(usersRouter); app.use(productsRouter); mounts without prefixes, so routes won't be under desired paths. app.use('/list', usersRouter); app.use('/list', productsRouter); mounts both under /list, causing conflicts. app.get('/users', usersRouter); app.get('/products', productsRouter); uses app.get incorrectly with routers.
  3. Final Answer:

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

    Mount routers with correct path prefixes [OK]
Hint: Use app.use with path prefix for each router [OK]
Common Mistakes:
  • Mounting routers without path prefix
  • Using app.get instead of app.use for routers
  • Mounting multiple routers on same path
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