Bird
Raised Fist0
Denoframework~10 mins

Deno.serve for HTTP handling - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Deno.serve for HTTP handling
Start Deno.serve
↓
Wait for HTTP Request
↓
Receive Request
↓
Call Handler Function
↓
Process Request & Create Response
↓
Send Response to Client
↓
Wait for Next Request
↩...loop...
Deno.serve starts a server that waits for HTTP requests, calls your handler function for each request, then sends back the response.
Execution Sample
Deno
Deno.serve(req => new Response("Hello from Deno!"));
This code starts a simple HTTP server that responds with "Hello from Deno!" to every request.
Execution Table
StepActionInputHandler OutputResponse Sent
1Server startsNo request yetNo handler callNo response
2Request receivedGET /Handler called with Request objectResponse("Hello from Deno!")
3Response sentN/AResponse("Hello from Deno!")Client receives "Hello from Deno!"
4Wait for next requestNo requestNo handler callNo response
💡 Server runs continuously until stopped manually
Variable Tracker
VariableStartAfter Step 2After Step 3Final
requndefinedRequest object for GET /Request object remainsRequest object remains
responseundefinedundefinedResponse("Hello from Deno!")Response object sent
Key Moments - 3 Insights
Why does the handler function get called multiple times?
Because the server waits for each new HTTP request and calls the handler every time a request arrives, as shown in execution_table steps 2 and 4.
What type of object does the handler receive?
The handler receives a Request object representing the incoming HTTP request, as shown in execution_table step 2 under Input.
What happens if the handler returns a Response object?
The server sends that Response back to the client, as shown in execution_table step 3 where the Response is sent.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the handler output at step 2?
AResponse("Hello from Deno!")
BHandler called with Request object
CNo handler call
DClient receives response
💡 Hint
Check the 'Handler Output' column at step 2 in execution_table
At which step does the client receive the response?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Response Sent' column in execution_table
If the handler returned a different Response, how would execution_table change?
AThe 'Handler Output' and 'Response Sent' columns at step 2 and 3 would show the new Response
BThe server would stop after one request
CThe 'Request' object would change
DNo changes would happen
💡 Hint
Focus on how the handler output and response sent columns reflect the handler's return value
Concept Snapshot
Deno.serve starts an HTTP server.
It waits for requests.
Calls your handler function with each Request.
Handler returns a Response.
Server sends Response back to client.
Runs continuously until stopped.
Full Transcript
Deno.serve is a simple way to create an HTTP server in Deno. When you call Deno.serve with a handler function, it starts listening for HTTP requests. Each time a request comes in, Deno calls your handler function with a Request object. Your handler processes the request and returns a Response object. Deno then sends this response back to the client. This cycle repeats for every new request until you stop the server. This makes it easy to build web servers that respond to HTTP requests in Deno.

Practice

(1/5)
1. What does Deno.serve primarily do in a Deno application?
easy
A. It creates a simple HTTP server that listens for requests.
B. It compiles TypeScript code into JavaScript.
C. It manages database connections automatically.
D. It formats JSON data for API responses.

Solution

  1. Step 1: Understand the purpose of Deno.serve

    Deno.serve is designed to start an HTTP server that listens for incoming requests.
  2. Step 2: Compare options with this purpose

    Only It creates a simple HTTP server that listens for requests. describes creating an HTTP server. Other options describe unrelated tasks.
  3. Final Answer:

    It creates a simple HTTP server that listens for requests. -> Option A
  4. Quick Check:

    Deno.serve creates HTTP server [OK]
Hint: Deno.serve starts a server to handle HTTP requests [OK]
Common Mistakes:
  • Confusing Deno.serve with code compilation
  • Thinking it manages databases
  • Assuming it formats data automatically
2. Which of the following is the correct way to use Deno.serve to respond with "Hello World" to every request?
easy
A. Deno.serve(() => new Response.text("Hello World"));
B. Deno.serve(request => Response("Hello World"));
C. Deno.serve(() => Response.text("Hello World"));
D. Deno.serve(() => new Response("Hello World"));

Solution

  1. Step 1: Check the correct Response object creation

    In Deno, to send a response, you create a new Response object with the body text.
  2. Step 2: Validate syntax of each option

    Deno.serve(() => new Response("Hello World")); correctly uses new Response("Hello World"). Options A, B, and C misuse Response creation or methods.
  3. Final Answer:

    Deno.serve(() => new Response("Hello World")); -> Option D
  4. Quick Check:

    Use new Response() to send reply [OK]
Hint: Always use new Response() to send HTTP replies [OK]
Common Mistakes:
  • Omitting 'new' keyword before Response
  • Using Response as a function instead of a constructor
  • Calling non-existent Response.text method
3. What will the following code output when accessed via a browser?
import { serve } from "https://deno.land/std/http/server.ts";

Deno.serve(req => {
  if (req.url.endsWith("/json")) {
    return new Response(JSON.stringify({ message: "Hi" }), {
      headers: { "Content-Type": "application/json" },
    });
  }
  return new Response("Not JSON");
});
medium
A. The browser shows: Not JSON
B. The browser shows: {"message":"Hi"} with JSON content type
C. The browser shows a 404 error
D. The server crashes with an error

Solution

  1. Step 1: Analyze the request URL condition

    The code checks if the URL ends with '/json'. If yes, it returns JSON; otherwise, it returns "Not JSON".
  2. Step 2: Determine the output for a normal browser request

    A browser accessing the root URL (e.g., http://localhost:8000/) does not end with '/json', so it returns "Not JSON" as plain text.
  3. Final Answer:

    The browser shows: Not JSON -> Option A
  4. Quick Check:

    URL ends with '/json'? No = "Not JSON" [OK]
Hint: Check URL endings carefully to predict response [OK]
Common Mistakes:
  • Assuming all requests return JSON
  • Ignoring URL path in condition
  • Expecting server errors without syntax issues
4. Identify the error in this Deno.serve usage:
Deno.serve(async (req) => {
  const data = await req.json();
  return new Response(data);
});
medium
A. Cannot call req.json() on a Request object
B. Response constructor expects a string or Uint8Array, not an object
C. Missing await before new Response()
D. Deno.serve does not support async functions

Solution

  1. Step 1: Understand req.json() usage

    Calling await req.json() correctly parses JSON body from the request.
  2. Step 2: Check Response constructor argument

    The Response constructor expects a string or binary data, but data is an object, causing a type error.
  3. Final Answer:

    Response constructor expects a string or Uint8Array, not an object -> Option B
  4. Quick Check:

    Response body must be string or bytes, not object [OK]
Hint: Always stringify objects before passing to Response [OK]
Common Mistakes:
  • Passing raw object to Response instead of string
  • Thinking req.json() is invalid on Request
  • Assuming async functions are unsupported
5. You want to create a Deno server that responds with "Hello, {name}!" where {name} is a query parameter from the URL (e.g., /?name=Alice). Which code snippet correctly implements this?
hard
A. Deno.serve(req => { const url = req.url; const name = url.params.name || 'Guest'; return new Response(`Hello, ${name}!`); });
B. Deno.serve(req => { const name = req.query.name || 'Guest'; return new Response(`Hello, ${name}!`); });
C. Deno.serve(req => { const url = new URL(req.url); const name = url.searchParams.get('name') || 'Guest'; return new Response(`Hello, ${name}!`); });
D. Deno.serve(req => { const name = req.get('name') || 'Guest'; return new Response(`Hello, ${name}!`); });

Solution

  1. Step 1: Extract query parameters from request URL

    Use new URL(req.url) to parse the URL and access searchParams for query parameters.
  2. Step 2: Get 'name' parameter safely and respond

    Use url.searchParams.get('name') with fallback to 'Guest', then return a Response with the greeting string.
  3. Final Answer:

    Deno.serve(req => { const url = new URL(req.url); const name = url.searchParams.get('name') || 'Guest'; return new Response(`Hello, ${name}!`); }); -> Option C
  4. Quick Check:

    Use URL and searchParams to read query [OK]
Hint: Parse req.url with URL to access query parameters [OK]
Common Mistakes:
  • Assuming req has query or params properties
  • Trying to get query params directly from req
  • Using non-existent req.get() method
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