Bird
Raised Fist0
Denoframework~20 mins

Middleware patterns in Deno - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Middleware Execution Order in Deno
Consider a Deno server using middleware functions added in this order:

1. Middleware A logs "Start A" and calls next()
2. Middleware B logs "Start B" and calls next()
3. Middleware C logs "Start C" and does NOT call next()

What will be the order of console logs when a request is handled?
Deno
import { Application } from "https://deno.land/x/oak/mod.ts";
const app = new Application();

app.use(async (ctx, next) => {
  console.log("Start A");
  await next();
  console.log("End A");
});

app.use(async (ctx, next) => {
  console.log("Start B");
  await next();
  console.log("End B");
});

app.use(async (ctx, next) => {
  console.log("Start C");
  // no next() call here
});

app.listen({ port: 8000 });
A"Start A", "Start B", "Start C", "End B", "End A"
B"Start A", "Start B", "Start C"
C"Start C", "Start B", "Start A"
D"Start A", "Start C", "Start B"
Attempts:
2 left
💡 Hint
Remember that middleware calls next() to pass control and that code after await next() runs after downstream middleware finish.
❓ state_output
intermediate
2:00remaining
Modifying Context in Middleware
In a Deno Oak app, middleware A sets ctx.state.user = 'Alice'. Middleware B reads ctx.state.user and appends ' logged in'. What is the value of ctx.state.user after both middlewares run?
Deno
import { Application } from "https://deno.land/x/oak/mod.ts";
const app = new Application();

app.use(async (ctx, next) => {
  ctx.state.user = "Alice";
  await next();
});

app.use(async (ctx, next) => {
  ctx.state.user += " logged in";
  await next();
});

app.use((ctx) => {
  ctx.response.body = ctx.state.user;
});

app.listen({ port: 8000 });
Aundefined
B"Alice"
C" logged in"
D"Alice logged in"
Attempts:
2 left
💡 Hint
ctx.state is shared across middleware during a request.
📝 Syntax
advanced
2:00remaining
Identify the Syntax Error in Middleware
Which middleware function below will cause a syntax error in Deno Oak?
Aasync (ctx, next) => { await next(); console.log("Done"); }
B} ;)"enoD"(gol.elosnoc ;)(txen tiawa { >= )txen ,xtc( cnysa
Csync (ctx, next) => { await next(); console.log("Done"); }
Dasync (ctx, next) => { await next(); console.log("Done");
Attempts:
2 left
💡 Hint
Check for missing semicolons or syntax mistakes.
🔧 Debug
advanced
2:00remaining
Why Does This Middleware Not Pass Control?
Given this middleware, why does the request hang and never reach the response handler?

async (ctx, next) => { console.log("Middleware start"); }
Deno
async (ctx, next) => { console.log("Middleware start"); }
ABecause ctx is not passed to next(), causing an error.
BBecause it does not call await next(), so the chain stops here.
CBecause console.log is asynchronous and blocks the chain.
DBecause the function is not marked async.
Attempts:
2 left
💡 Hint
Middleware must call next() to continue the chain.
🧠 Conceptual
expert
2:00remaining
Middleware Pattern Purpose in Deno
What is the main purpose of using middleware patterns in a Deno web server framework like Oak?
ATo speed up server startup by preloading all routes at once.
BTo replace the need for routing by handling all requests in one function.
CTo modularize request processing by chaining functions that can modify request and response objects.
DTo automatically generate HTML pages without manual coding.
Attempts:
2 left
💡 Hint
Think about how middleware helps organize code and handle requests step-by-step.

Practice

(1/5)
1. What is the main purpose of middleware in a Deno web application?
easy
A. To compile TypeScript code into JavaScript
B. To store data permanently in a database
C. To run code step-by-step for each incoming request
D. To create user interface components

Solution

  1. Step 1: Understand middleware role

    Middleware processes each request in order, allowing code to run before sending a response.
  2. Step 2: Compare options

    Only To run code step-by-step for each incoming request describes this step-by-step request handling. Other options describe unrelated tasks.
  3. Final Answer:

    To run code step-by-step for each incoming request -> Option C
  4. Quick Check:

    Middleware = step-by-step request code [OK]
Hint: Middleware runs code for each request in order [OK]
Common Mistakes:
  • Confusing middleware with database operations
  • Thinking middleware builds UI components
  • Assuming middleware compiles code
2. Which of the following is the correct way to call the next middleware in Deno?
easy
A. next.await()
B. next()
C. call next()
D. await next()

Solution

  1. Step 1: Recall async middleware pattern

    Middleware functions are async and must await next() to continue the chain.
  2. Step 2: Check syntax correctness

    Only 'await next()' correctly waits for the next middleware to finish before continuing.
  3. Final Answer:

    await next() -> Option D
  4. Quick Check:

    Use await next() to proceed [OK]
Hint: Always use await before next() in async middleware [OK]
Common Mistakes:
  • Calling next() without await causing unexpected behavior
  • Using incorrect syntax like call next()
  • Trying to use next.await() which is invalid
3. Given this middleware code snippet in Deno:
async function logger(ctx, next) {
  console.log('Before');
  await next();
  console.log('After');
}

async function handler(ctx) {
  ctx.response.body = 'Hello';
}

// Middleware chain: logger -> handler
What will be printed to the console when a request is handled?
medium
A. Before\nAfter
B. After\nBefore
C. Before
D. After

Solution

  1. Step 1: Analyze middleware flow

    Logger prints 'Before', then awaits next middleware (handler), then prints 'After'.
  2. Step 2: Understand order of prints

    Since handler runs between the two console.logs, output order is 'Before' then 'After'.
  3. Final Answer:

    Before\nAfter -> Option A
  4. Quick Check:

    Middleware logs before and after next() [OK]
Hint: Middleware logs before and after await next() [OK]
Common Mistakes:
  • Assuming 'After' prints before 'Before'
  • Thinking only 'Before' or 'After' prints
  • Ignoring await causing wrong order
4. Identify the error in this Deno middleware code:
async function auth(ctx, next) {
  if (!ctx.request.headers.get('Authorization')) {
    ctx.response.status = 401;
    ctx.response.body = 'Unauthorized';
  }
  await next();
}
medium
A. Missing await before ctx.request.headers.get
B. Should return after setting 401 to stop middleware chain
C. ctx.response.body must be a JSON object
D. next() should not be awaited

Solution

  1. Step 1: Understand middleware flow control

    If authorization header is missing, response is set to 401, but code still calls await next(), continuing the chain.
  2. Step 2: Identify fix to stop chain

    To prevent further middleware running, function should return immediately after setting 401 response.
  3. Final Answer:

    Should return after setting 401 to stop middleware chain -> Option B
  4. Quick Check:

    Return early to stop middleware chain [OK]
Hint: Return after response to stop middleware chain [OK]
Common Mistakes:
  • Not returning causes next middleware to run anyway
  • Thinking await is missing on header get
  • Believing response body must be JSON always
5. You want to create a middleware in Deno that measures how long each request takes and adds a custom header X-Response-Time with the duration in milliseconds. Which of the following middleware implementations correctly achieves this?
hard
A. async function responseTime(ctx, next) { const start = performance.now(); await next(); const ms = performance.now() - start; ctx.response.headers.set('X-Response-Time', ms.toFixed(2)); }
B. async function responseTime(ctx, next) { const start = Date.now(); const ms = Date.now() - start; ctx.response.headers.set('X-Response-Time', `${ms}ms`); await next(); }
C. async function responseTime(ctx, next) { const start = Date.now(); next(); const ms = Date.now() - start; ctx.response.headers.set('X-Response-Time', `${ms}ms`); }
D. async function responseTime(ctx, next) { await next(); const ms = Date.now(); ctx.response.headers.set('X-Response-Time', ms); }

Solution

  1. Step 1: Measure time before and after next()

    Start timer before await next(), then calculate duration after it finishes.
  2. Step 2: Use precise timer and set header correctly

    performance.now() gives better precision than Date.now(). Setting header with ms.toFixed(2) formats nicely.
  3. Final Answer:

    Middleware using performance.now(), await next(), and setting header after next() -> Option A
  4. Quick Check:

    Use performance.now() and await next() then set header [OK]
Hint: Start timer before await next(), set header after [OK]
Common Mistakes:
  • Calculating time before await next() runs
  • Using Date.now() which is less precise
  • Setting header before next() completes
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