Bird
Raised Fist0
Denoframework~10 mins

Routes and layouts in Deno - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Routes and layouts
User requests URL
↓
Router matches route
↓
Select layout for route
↓
Render layout
↓
Render page content inside layout
↓
Send complete HTML to browser
When a user visits a URL, the router finds the matching route, applies the layout, renders the page inside it, and sends the full page to the browser.
Execution Sample
Deno
import { Router } from "https://deno.land/x/oak/mod.ts";

const router = new Router();

router.get('/', ctx => {
  ctx.response.body = `<main><h1>Home</h1></main>`;
});
This code sets up a route for '/' that sends a simple home page wrapped in a main layout.
Execution Table
StepActionRoute MatchedLayout SelectedPage Content RenderedResponse Sent
1User visits '/' URLNoNoNoNo
2Router checks routesYes ('/')NoNoNo
3Select layout for '/'YesMain layoutNoNo
4Render layoutYesMain layoutNoNo
5Render page content inside layoutYesMain layout<h1>Home</h1>No
6Send full HTML responseYesMain layout<h1>Home</h1>Yes
💡 Response sent to browser, request cycle complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
routeMatchedfalsetruetruetruetrue
layoutnullnullMain layoutMain layoutMain layout
pageContentnullnullnull<h1>Home</h1><h1>Home</h1>
responseSentfalsefalsefalsefalsetrue
Key Moments - 3 Insights
Why does the layout get selected after the route is matched?
Because the layout depends on which route is active, the router must first find the route before choosing the correct layout (see execution_table step 3).
Is the page content rendered before or after the layout?
The layout renders first as a container, then the page content is inserted inside it (see execution_table steps 4 and 5).
When is the full response sent to the browser?
Only after the layout and page content are combined and rendered fully (see execution_table step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the route matched?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Check the 'Route Matched' column in the execution_table rows
According to variable_tracker, what is the value of 'responseSent' after step 5?
Afalse
Bnull
Ctrue
Dundefined
💡 Hint
Look at the 'responseSent' row and the 'After Step 5' column in variable_tracker
If the layout was not selected, what would happen at step 5 in the execution table?
ARoute would not be matched
BPage content would render without a layout
CResponse would be sent immediately
DUser would see a 404 error
💡 Hint
Refer to the 'Layout Selected' and 'Page Content Rendered' columns in execution_table
Concept Snapshot
Routes and layouts in Deno:
- User visits URL
- Router matches route
- Layout chosen based on route
- Layout renders as page container
- Page content renders inside layout
- Full HTML sent to browser
Layouts keep pages consistent and organized.
Full Transcript
When a user visits a URL in a Deno web app, the router first checks which route matches the URL. Once the route is found, the app selects the appropriate layout for that route. The layout acts like a frame or container for the page content. The layout renders first, then the page content is inserted inside it. Finally, the combined HTML is sent as the response to the browser. This process ensures pages have consistent structure and style. The execution table shows each step from user request to response sent. The variable tracker follows key variables like routeMatched, layout, pageContent, and responseSent as they change. Common confusions include why layout selection happens after route matching, and when the full response is sent. The visual quiz tests understanding of these steps by referencing the tables. This step-by-step flow helps beginners see how routes and layouts work together in Deno apps.

Practice

(1/5)
1. What is the main purpose of routes in a Deno web application?
easy
A. To store user data in a database
B. To style the application with CSS
C. To connect URLs to specific content or pages
D. To handle server hardware settings

Solution

  1. Step 1: Understand what routes do

    Routes link a URL path to the content or page that should show when that URL is visited.
  2. Step 2: Compare options to this definition

    Only To connect URLs to specific content or pages describes connecting URLs to content, which matches the purpose of routes.
  3. Final Answer:

    To connect URLs to specific content or pages -> Option C
  4. Quick Check:

    Routes = URL to content connection [OK]
Hint: Routes map URLs to pages or content [OK]
Common Mistakes:
  • Confusing routes with styling or database tasks
  • Thinking routes manage server hardware
  • Mixing routes with layout responsibilities
2. Which of the following is the correct way to define a route handler in a Deno Oak application?
easy
A. router.route('/home', function() { return 'Home'; });
B. router.get('/home', (ctx) => { ctx.response.body = 'Home'; });
C. router.add('/home', (req, res) => res.send('Home'));
D. router.handle('/home', () => { print('Home'); });

Solution

  1. Step 1: Recall Oak router syntax

    In Oak, routes are defined using methods like router.get(path, handler).
  2. Step 2: Check each option's syntax

    router.get('/home', (ctx) => { ctx.response.body = 'Home'; }); uses router.get with a context parameter and sets ctx.response.body, which is correct Oak syntax.
  3. Final Answer:

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

    Oak route syntax = router.get(path, ctx) [OK]
Hint: Use router.get with ctx and set ctx.response.body [OK]
Common Mistakes:
  • Using non-existent router methods like add or handle
  • Not setting ctx.response.body for response
  • Confusing callback parameters with Express.js style
3. Given this Deno Oak route and layout setup, what will be the output when visiting '/about'?
const router = new Router();
router.get('/about', (ctx) => { ctx.response.body = 'About Page'; });

const layout = (content) => `
Header
${content}
Footer
`; // Middleware to wrap response app.use(async (ctx, next) => { await next(); ctx.response.body = layout(ctx.response.body); }); app.use(router.routes()); app.use(router.allowedMethods());
medium
A.
Header
About Page
Footer
B. About Page
C.
Header
Footer
D. Error: layout function not applied

Solution

  1. Step 1: Understand route response

    The route sets ctx.response.body to 'About Page' when '/about' is visited.
  2. Step 2: Understand middleware wrapping

    The middleware runs after the route, wrapping the body with header and footer HTML using the layout function.
  3. Final Answer:

    <header>Header</header>About Page<footer>Footer</footer> -> Option A
  4. Quick Check:

    Middleware wraps route output with layout [OK]
Hint: Middleware modifies response after route sets it [OK]
Common Mistakes:
  • Ignoring middleware wrapping
  • Assuming route output is unchanged
  • Confusing order of middleware and routes
4. Identify the error in this Deno Oak route and layout code snippet:
const router = new Router();
router.get('/contact', (ctx) => {
  ctx.response.body = 'Contact Page';
});

const layout = (content) => `
Header
${content}
Footer
`; app.use(router.routes()); app.use(router.allowedMethods()); app.use(async (ctx, next) => { await next(); ctx.response.body = layout(ctx.response.body); });
medium
A. router.allowedMethods() is missing
B. Middleware wrapping layout runs after routes, so layout is applied too late
C. ctx.response.body is not set in route handler
D. Middleware wrapping layout runs after routes, so layout is not applied

Solution

  1. Step 1: Analyze middleware order

    router.routes() and router.allowedMethods() are registered before the layout middleware.
  2. Step 2: Recall route handler behavior in Oak

    When router.routes() matches a route, it executes the handler. The handler sets the response body but does not call next(), terminating the middleware chain at that point.
  3. Step 3: Determine layout application

    Subsequent middleware, including the layout wrapper, are never reached for matched routes. Thus, the layout is not applied.
  4. Final Answer:

    Middleware wrapping layout runs after routes, so layout is not applied -> Option D
  5. Quick Check:

    Middleware after router.routes() skipped on match [OK]
Hint: Layout middleware must precede router.routes() [OK]
Common Mistakes:
  • Placing layout middleware after routes
  • Forgetting to set ctx.response.body in route
  • Misunderstanding middleware execution order
5. You want to create a Deno Oak app with a layout that adds a header and footer to all pages, but only for routes under '/app'. Which approach correctly applies the layout only to those routes?
hard
A. Use a middleware that checks if ctx.request.url.pathname starts with '/app' and wraps response body with layout only then
B. Apply the layout middleware globally to all routes without condition
C. Add the header and footer HTML directly inside each route handler under '/app'
D. Use router.allowedMethods() to apply layout only to '/app' routes

Solution

  1. Step 1: Understand the requirement

    The layout should wrap only routes under '/app', not all routes.
  2. Step 2: Evaluate each option

    Use a middleware that checks if ctx.request.url.pathname starts with '/app' and wraps response body with layout only then uses middleware that checks the URL path and applies layout conditionally, which is correct and efficient.
  3. Step 3: Why other options fail

    Apply the layout middleware globally to all routes without condition applies layout to all routes, ignoring the condition. Add the header and footer HTML directly inside each route handler under '/app' duplicates layout code in every route, which is not DRY. Use router.allowedMethods() to apply layout only to '/app' routes misuses router.allowedMethods(), which only handles HTTP method responses.
  4. Final Answer:

    Use a middleware that checks if ctx.request.url.pathname starts with '/app' and wraps response body with layout only then -> Option A
  5. Quick Check:

    Conditional middleware applies layout selectively [OK]
Hint: Check URL path in middleware to apply layout selectively [OK]
Common Mistakes:
  • Applying layout middleware globally without condition
  • Repeating layout code in each route
  • Misusing router.allowedMethods() for layout
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