Middleware helps your app handle tasks step-by-step, like checking users or logging info, before doing the main work.
Middleware patterns in Deno
async function middleware(ctx, next) { // Do something before await next(); // Do something after }
ctx is the context of the request and response.
next() calls the next middleware in the chain.
async function logger(ctx, next) { console.log(`Request: ${ctx.request.method} ${ctx.request.url}`); await next(); console.log(`Response status: ${ctx.response.status}`); }
async function auth(ctx, next) { if (!ctx.request.headers.get('Authorization')) { ctx.response.status = 401; ctx.response.body = 'Unauthorized'; return; } await next(); }
This Deno Oak app uses middleware to log requests, check authorization, and then respond. If no Authorization header is sent, it replies with 401 Unauthorized. Otherwise, it says hello.
import { Application } from "https://deno.land/x/oak@v12.5.0/mod.ts"; const app = new Application(); // Logger middleware app.use(async (ctx, next) => { console.log(`Request: ${ctx.request.method} ${ctx.request.url}`); await next(); console.log(`Response status: ${ctx.response.status}`); }); // Simple auth middleware app.use(async (ctx, next) => { if (!ctx.request.headers.get('Authorization')) { ctx.response.status = 401; ctx.response.body = 'Unauthorized'; return; } await next(); }); // Main response app.use((ctx) => { ctx.response.body = 'Hello, authorized user!'; }); console.log('Server running on http://localhost:8000'); await app.listen({ port: 8000 });
Always call await next() to continue to the next middleware unless you want to stop the chain.
Order matters: middleware runs in the order you add it.
Middleware can do work before and after next(), like logging or modifying responses.
Middleware runs code step-by-step for each request.
Use ctx to access request and response info.
Call await next() to move to the next middleware.
Practice
Solution
Step 1: Understand middleware role
Middleware processes each request in order, allowing code to run before sending a response.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.Final Answer:
To run code step-by-step for each incoming request -> Option CQuick Check:
Middleware = step-by-step request code [OK]
- Confusing middleware with database operations
- Thinking middleware builds UI components
- Assuming middleware compiles code
Solution
Step 1: Recall async middleware pattern
Middleware functions are async and must await next() to continue the chain.Step 2: Check syntax correctness
Only 'await next()' correctly waits for the next middleware to finish before continuing.Final Answer:
await next() -> Option DQuick Check:
Use await next() to proceed [OK]
- Calling next() without await causing unexpected behavior
- Using incorrect syntax like call next()
- Trying to use next.await() which is invalid
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?Solution
Step 1: Analyze middleware flow
Logger prints 'Before', then awaits next middleware (handler), then prints 'After'.Step 2: Understand order of prints
Since handler runs between the two console.logs, output order is 'Before' then 'After'.Final Answer:
Before\nAfter -> Option AQuick Check:
Middleware logs before and after next() [OK]
- Assuming 'After' prints before 'Before'
- Thinking only 'Before' or 'After' prints
- Ignoring await causing wrong order
async function auth(ctx, next) {
if (!ctx.request.headers.get('Authorization')) {
ctx.response.status = 401;
ctx.response.body = 'Unauthorized';
}
await next();
}Solution
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.Step 2: Identify fix to stop chain
To prevent further middleware running, function should return immediately after setting 401 response.Final Answer:
Should return after setting 401 to stop middleware chain -> Option BQuick Check:
Return early to stop middleware chain [OK]
- Not returning causes next middleware to run anyway
- Thinking await is missing on header get
- Believing response body must be JSON always
X-Response-Time with the duration in milliseconds. Which of the following middleware implementations correctly achieves this?Solution
Step 1: Measure time before and after next()
Start timer before await next(), then calculate duration after it finishes.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.Final Answer:
Middleware using performance.now(), await next(), and setting header after next() -> Option AQuick Check:
Use performance.now() and await next() then set header [OK]
- Calculating time before await next() runs
- Using Date.now() which is less precise
- Setting header before next() completes
Ready to prove it?
Pass the test and this pattern moves unknown
