Bird
Raised Fist0
Denoframework~5 mins

Deno.serve for HTTP handling

Choose your learning style10 modes available
Introduction
Deno.serve lets you quickly create a simple web server to handle HTTP requests and send responses. It makes building web apps easy without extra setup.
You want to create a small web server to serve web pages or APIs.
You need to handle HTTP requests like GET or POST in a simple way.
You want to test or prototype a web service quickly on your computer.
You want to learn how servers work by writing minimal code.
You want to build a backend for a web or mobile app without complex tools.
Syntax
Deno
Deno.serve(async (request) => {
  // handle request and return response
  return new Response("Hello World", { status: 200 });
});
The function inside Deno.serve receives each HTTP request as a Request object.
You return a Response object to send data back to the client.
Examples
A simple server that always responds with the same text.
Deno
Deno.serve(() => new Response("Hello from Deno!"));
Server that checks the request method and responds accordingly.
Deno
Deno.serve(async (req) => {
  if (req.method === "GET") {
    return new Response("You sent a GET request");
  } else {
    return new Response("Only GET allowed", { status: 405 });
  }
});
Server that responds differently based on the URL path.
Deno
Deno.serve(async (req) => {
  const url = new URL(req.url);
  if (url.pathname === "/hello") {
    return new Response("Hello there!");
  }
  return new Response("Not found", { status: 404 });
});
Sample Program
This server responds with different messages for '/' and '/about' paths. Other paths return a 404 error.
Deno
Deno.serve(async (request) => {
  const url = new URL(request.url);
  if (url.pathname === "/") {
    return new Response("Welcome to the homepage!", {
      headers: { "content-type": "text/plain; charset=utf-8" },
    });
  } else if (url.pathname === "/about") {
    return new Response("This is the about page.", {
      headers: { "content-type": "text/plain; charset=utf-8" },
    });
  } else {
    return new Response("Page not found", { status: 404 });
  }
});
OutputSuccess
Important Notes
Deno.serve automatically listens on port 8000 by default.
You can stop the server by pressing Ctrl+C in the terminal.
Use browser or tools like curl to test your server responses.
Summary
Deno.serve creates a simple HTTP server with minimal code.
It handles requests by running your function for each HTTP call.
You return Response objects to send data back to clients.

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