Bird
Raised Fist0
Denoframework~10 mins

Routing patterns in Deno - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Routing patterns
Incoming HTTP Request
↓
Match URL Path with Route Patterns
↓
Exact Match
↓
Call Handler
↓
Send Response
The server receives a request, matches its URL to defined route patterns (exact, parameterized, or wildcard), then calls the matching handler to respond.
Execution Sample
Deno
import { serve } from "https://deno.land/std/http/server.ts";

serve(req => {
  const url = new URL(req.url);
  if (url.pathname === "/") return new Response("Home");
  if (url.pathname.startsWith("/user/")) {
    const id = url.pathname.split("/")[2];
    return new Response(`User ID: ${id}`);
  }
  return new Response("Not Found", { status: 404 });
});
This code listens for HTTP requests and routes them based on the URL path: exact match for home, parameterized for user ID, else 404.
Execution Table
StepRequest URLRoute Pattern CheckedMatch ResultAction TakenResponse
1http://localhost/"/"Exact matchCall home handler"Home"
2http://localhost/user/42"/"No matchCheck next patternN/A
3http://localhost/user/42"/user/:id"Parameterized matchExtract id=42, call user handler"User ID: 42"
4http://localhost/about"/"No matchCheck next patternN/A
5http://localhost/about"/user/:id"No matchCheck next patternN/A
6http://localhost/aboutNo more patternsNo matchReturn 404"Not Found"
💡 Routing stops when a matching pattern is found or all patterns are checked with no match.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 6
url.pathnameundefined"/""/user/42""/about"
idundefinedundefined"42"undefined
responseundefined"Home""User ID: 42""Not Found"
Key Moments - 3 Insights
Why does the code check the exact path '/' before the parameterized '/user/:id'?
Because exact matches are more specific and should be checked first to avoid catching parameterized routes too early, as shown in steps 1 and 2 of the execution_table.
How is the user ID extracted from the URL in the parameterized route?
The code splits the pathname by '/' and takes the third part as the ID, as seen in step 3 where id becomes '42'.
What happens if no route patterns match the request URL?
The server returns a 404 response, as shown in step 6 where no patterns match and 'Not Found' is returned.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response when the request URL is 'http://localhost/user/42'?
A"User ID: 42"
B"Home"
C"Not Found"
DNo response
💡 Hint
Check step 3 in the execution_table where the parameterized route matches and returns the user ID.
At which step does the routing process return a 404 response?
AStep 4
BStep 6
CStep 2
DStep 1
💡 Hint
Look at the last step in the execution_table where no patterns match and 404 is returned.
If the code checked the parameterized route before the exact '/', what would happen for the URL '/'?
AIt would cause an error
BIt would still match '/' correctly
CIt would match the parameterized route incorrectly
DIt would return 404
💡 Hint
Refer to the order of checks in steps 1 and 2 in the execution_table and how order affects matching.
Concept Snapshot
Routing patterns match incoming URLs to handlers.
Exact matches check for exact path equality.
Parameterized routes extract parts of the path as variables.
Order matters: check exact before parameterized.
If no match, return 404 response.
Handlers return responses based on matched route.
Full Transcript
Routing patterns in Deno handle incoming HTTP requests by matching the URL path to predefined patterns. The server first checks for exact matches, like the root path '/'. If no exact match is found, it checks parameterized routes that extract variables from the URL, such as '/user/:id'. If still no match, it returns a 404 Not Found response. This process ensures requests are routed to the correct handler based on the URL structure. The order of checking routes is important to avoid incorrect matches. For example, checking exact paths before parameterized ones prevents the root path from being misinterpreted as a parameter. This visual execution shows step-by-step how requests are matched and how variables like 'id' are extracted and used in responses.

Practice

(1/5)
1. What is the main purpose of routing patterns in a Deno web application?
easy
A. To store data in a database
B. To style the webpage with colors and fonts
C. To connect URLs to specific code that runs when those URLs are visited
D. To manage user authentication only

Solution

  1. Step 1: Understand routing role

    Routing connects web addresses (URLs) to the code that should run when those addresses are accessed.
  2. Step 2: Compare options

    Only To connect URLs to specific code that runs when those URLs are visited describes this connection. Other options describe unrelated tasks like styling or data storage.
  3. Final Answer:

    To connect URLs to specific code that runs when those URLs are visited -> Option C
  4. Quick Check:

    Routing = URL to code connection [OK]
Hint: Routing links URLs to code that runs on visit [OK]
Common Mistakes:
  • Confusing routing with styling or database tasks
  • Thinking routing only manages user login
  • Believing routing changes page colors
2. Which of the following is the correct way to define a static route using Oak in Deno?
easy
A. router.get('/home', (ctx) => { ctx.response.body = 'Welcome'; });
B. router.route('/home', (ctx) => { ctx.body = 'Welcome'; });
C. router.add('/home', (ctx) => { ctx.response.body = 'Welcome'; });
D. router.get('/home', (ctx) => { return 'Welcome'; });

Solution

  1. Step 1: Recall Oak routing syntax

    Oak uses router.get(path, handler) to define GET routes. The handler sets ctx.response.body for response content.
  2. Step 2: Check each option

    router.get('/home', (ctx) => { ctx.response.body = 'Welcome'; }); matches correct syntax. router.route('/home', (ctx) => { ctx.body = 'Welcome'; }); uses non-existent method 'route'. router.add('/home', (ctx) => { ctx.response.body = 'Welcome'; }); uses 'add' which is invalid. router.get('/home', (ctx) => { return 'Welcome'; }); returns string instead of setting ctx.response.body.
  3. Final Answer:

    router.get('/home', (ctx) => { ctx.response.body = 'Welcome'; }); -> Option A
  4. Quick Check:

    Oak static route uses router.get and ctx.response.body [OK]
Hint: Use router.get and set ctx.response.body for static routes [OK]
Common Mistakes:
  • Using wrong router method like route or add
  • Returning string instead of setting ctx.response.body
  • Forgetting to set response body
3. Given this Oak route code in Deno:
router.get('/user/:id', (ctx) => {
  const id = ctx.params.id;
  ctx.response.body = `User ID is ${id}`;
});

// Request URL: /user/42

What will be the response body when visiting /user/42?
medium
A. "User ID is :id"
B. "User ID is 42"
C. "User ID is undefined"
D. "User ID is /user/42"

Solution

  1. Step 1: Understand dynamic route parameter

    The route uses ':id' as a placeholder. When URL is '/user/42', ctx.params.id becomes '42'.
  2. Step 2: Check response body construction

    The response body uses template string to insert id value, so it becomes 'User ID is 42'.
  3. Final Answer:

    "User ID is 42" -> Option B
  4. Quick Check:

    Dynamic param ':id' = '42' in response [OK]
Hint: Dynamic params fill ctx.params with URL parts [OK]
Common Mistakes:
  • Using literal ':id' instead of param value
  • Forgetting to access ctx.params.id
  • Assuming undefined if param missing
4. Identify the error in this Oak routing code snippet:
router.get('/post/:postId', (ctx) => {
  const postId = ctx.request.params.postId;
  ctx.response.body = `Post: ${postId}`;
});
medium
A. ctx.response.body cannot be a template string
B. Missing async keyword in handler
C. Route path should not have colon before postId
D. ctx.request.params is undefined; should use ctx.params

Solution

  1. Step 1: Check how to access route params in Oak

    Route parameters are accessed via ctx.params, not ctx.request.params.
  2. Step 2: Verify other parts

    Async is not required here. Colon before postId is correct for dynamic routes. Template strings are valid for response body.
  3. Final Answer:

    ctx.request.params is undefined; should use ctx.params -> Option D
  4. Quick Check:

    Use ctx.params for route parameters [OK]
Hint: Use ctx.params, not ctx.request.params for route params [OK]
Common Mistakes:
  • Accessing params from ctx.request instead of ctx
  • Thinking async is mandatory for all handlers
  • Removing colon from dynamic route path
5. You want to create a Deno Oak route that matches URLs like /product/123/review/456 where 123 is the product ID and 456 is the review ID. Which route pattern correctly captures both IDs as parameters?
hard
A. router.get('/product/:productId/review/:reviewId', (ctx) => { /* ... */ });
B. router.get('/product/:productId/:reviewId/review', (ctx) => { /* ... */ });
C. router.get('/product/review/:productId/:reviewId', (ctx) => { /* ... */ });
D. router.get('/product/:productId/review', (ctx) => { /* ... */ });

Solution

  1. Step 1: Analyze URL structure

    The URL has 'product', then product ID, then 'review', then review ID in order.
  2. Step 2: Match route pattern to URL

    router.get('/product/:productId/review/:reviewId', (ctx) => { /* ... */ }); matches this pattern exactly with dynamic segments ':productId' and ':reviewId' in correct places.
  3. Step 3: Check other options

    router.get('/product/:productId/:reviewId/review', (ctx) => { /* ... */ }); misplaces ':reviewId' before 'review' segment. router.get('/product/review/:productId/:reviewId', (ctx) => { /* ... */ }); swaps order. router.get('/product/:productId/review', (ctx) => { /* ... */ }); misses review ID parameter.
  4. Final Answer:

    router.get('/product/:productId/review/:reviewId', (ctx) => { /* ... */ }); -> Option A
  5. Quick Check:

    Dynamic segments match URL parts in order [OK]
Hint: Match URL parts exactly; use :param for dynamic segments [OK]
Common Mistakes:
  • Swapping order of dynamic segments and static parts
  • Omitting one of the dynamic parameters
  • Placing parameters in wrong URL positions
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