Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท HTTP Servers

Requests and Responses in Deno

Read query strings, JSON bodies, forms and headers from a Deno Request, build correct Responses with status codes, cookies and CORS headers, and handle errors and bad input safely.

Every Deno server is built from two web-standard classes: Request and Response. They are the same classes you use in the browser and in service workers, so what you learn here also applies to fetch, to Deno Deploy, and to edge runtimes. In this lesson you will take requests apart (URL, method, headers, body) and put responses together (status, headers, cookies, JSON) the way a careful API does.

The most important habit is to never trust the request. Anything a client sends can be missing, malformed or hostile, so each handler validates its input and answers with a clear status code.

Deno is not available in the editor, so Deno.* code is shown read-only. The runnable examples use Node 24, which has the same Request, Response, Headers, URL and FormData classes, so the logic carries over unchanged.

Taking a Request apart

TypeScript
Deno.serve(async (req) => {
  const url = new URL(req.url);

  req.method;                          // "GET", "POST", ...
  url.pathname;                        // "/users/7"
  url.searchParams.get("page");        // "2" or null
  req.headers.get("content-type");     // case-insensitive lookup
  req.headers.get("authorization");    // "Bearer ..." or null

  return new Response("ok");
});

Query parameters are always strings (or null). Convert and check them yourself:

TypeScript
const raw = url.searchParams.get("page") ?? "1";
const page = Number.parseInt(raw, 10);
if (!Number.isInteger(page) || page < 1) {
  return Response.json({ error: "page must be a positive integer" }, { status: 400 });
}

Reading the body

A body can be read once, with one of these methods:

Method Returns Use for
req.json() parsed value JSON APIs
req.text() string plain text, custom formats
req.formData() FormData HTML forms and file uploads
req.arrayBuffer() / req.blob() binary raw bytes
req.body ReadableStream large or streamed uploads

req.json() throws a SyntaxError on invalid JSON, so wrap it. Also check the declared size or read with a limit if you accept big bodies, because a client can send as much as it likes.

Building a Response

TypeScript
new Response(body, { status: 201, statusText: "Created", headers });

body may be a string, bytes, a Blob, FormData, a ReadableStream or null. Pick the status code with intent:

Code Meaning When
200 OK successful read
201 Created a POST created something (add a Location header)
204 No Content success with nothing to send, such as DELETE
301/302/307/308 Redirect moved resources (Location header)
400 Bad Request malformed input
401 / 403 Unauthorized / Forbidden not logged in / not allowed
404 Not Found no such route or record
405 Method Not Allowed wrong method (send an Allow header)
409 Conflict duplicate or version clash
415 Unsupported Media Type wrong Content-Type
422 Unprocessable Content well-formed but invalid data
429 Too Many Requests rate limiting
500 Server Error your bug

The standard library exports readable constants so you do not sprinkle magic numbers:

TypeScript
import { STATUS_CODE, STATUS_TEXT } from "jsr:@std/http/status";

return new Response(null, { status: STATUS_CODE.NoContent });

A JSON endpoint with validation

The handler below accepts POST /users with a JSON body, validates it, and answers with the right status code. It is a good template for your own API handlers, and it runs here as a Node stand-in with the same code you would write in Deno.

Node.js Validating a JSON request body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note the pattern: status code first, human-readable error second, and a consistent error shape ({ error } or { errors }) so clients can rely on it.

Forms and file uploads

HTML forms send application/x-www-form-urlencoded or multipart/form-data. Both are read with req.formData():

TypeScript
Deno.serve(async (req) => {
  if (req.method === "POST") {
    const form = await req.formData();
    const title = String(form.get("title") ?? "");
    const file = form.get("photo");              // File | string | null

    if (file instanceof File) {
      const bytes = new Uint8Array(await file.arrayBuffer());
      await Deno.writeFile(`./uploads/${crypto.randomUUID()}`, bytes);
    }
    return Response.redirect(new URL("/thanks", req.url), 303);
  }
  return new Response(
    `<form method="post" enctype="multipart/form-data">...</form>`,
    { headers: { "content-type": "text/html; charset=utf-8" } },
  );
});

Never use the uploaded file's own name as a path (a name like ../../etc/passwd is an attack) and check its size and type. Writing needs --allow-write=./uploads. After a successful form POST, answer with a 303 See Other redirect so a page refresh does not submit the form again.

Headers, cookies and CORS

Headers is case-insensitive and can hold several values per name. To set cookies, add Set-Cookie headers. The standard library has helpers:

TypeScript
import { deleteCookie, getCookies, setCookie } from "jsr:@std/http/cookie";

Deno.serve((req) => {
  const cookies = getCookies(req.headers);          // { theme: "dark" }
  const headers = new Headers();
  setCookie(headers, {
    name: "session",
    value: crypto.randomUUID(),
    httpOnly: true,       // not readable from JavaScript
    secure: true,         // HTTPS only
    sameSite: "Lax",
    path: "/",
    maxAge: 60 * 60 * 24,
  });
  return new Response(`theme=${cookies.theme ?? "light"}`, { headers });
});

Always set httpOnly, secure and a sameSite value on session cookies.

CORS matters when a page on one origin calls your API on another. The browser first sends an OPTIONS preflight request; you answer with Access-Control-* headers. The runnable example below shows the logic and a hand-written cookie parser to make the mechanics visible.

Node.js CORS preflight and cookie parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The allow-list matters: reflecting any Origin back, or using * together with cookies, defeats the point of CORS. The Vary: Origin header tells caches that the answer depends on who asked.

Handling errors in one place

Rather than try/catch in every route, wrap the handler once:

TypeScript
function safe(handler: (req: Request) => Promise<Response> | Response) {
  return async (req: Request): Promise<Response> => {
    try {
      return await handler(req);
    } catch (error) {
      console.error(req.method, req.url, error);     // full detail in logs
      return Response.json({ error: "Internal error" }, { status: 500 });  // little detail to the client
    }
  };
}

Deno.serve(safe(myHandler));

Log the cause, but never send stack traces or database messages to the client. The next lesson, Routing and Middleware, generalizes this wrapper into a middleware chain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which status code is the best answer to a successful POST that created a new record?

    201 Created, ideally with a Location header pointing to the new resource, tells the client that something was created.
  2. 2. What happens if you call req.json() twice on the same request?

    A body is a stream that can be consumed only once. Use req.clone() before reading if you need it twice.
  3. 3. Which status is most fitting for well-formed JSON that fails validation rules?

    The request was understood and parsed, but the data is invalid, which is the case 422 describes (400 is also commonly used for malformed input).
  4. 4. Why should you set httpOnly on a session cookie?

    HttpOnly cookies are sent with requests but are invisible to document.cookie, which limits the damage of an XSS bug.

Summary

  • Parse the URL with new URL(req.url); query values are strings and need validation.
  • Read a body once with json(), text(), formData(), arrayBuffer() or stream req.body.
  • Choose status codes deliberately and use one consistent error shape.
  • Use jsr:@std/http for status constants and cookie helpers; set httpOnly, secure and sameSite.
  • CORS needs an OPTIONS answer and an origin allow-list.
  • Catch errors in one wrapper, log the details and send the client a short message.

Next: Routing and Middleware