Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Deno Exercises, Review and Cheat Sheet

Test your Deno skills with eight exercises on servers, routing, rate limiting, CSV, tests, KV key design, permissions and Docker, with runnable solutions, review questions and a command cheat sheet.

Reading about Deno teaches you the vocabulary; writing code teaches you the language. This final lesson gives you eight exercises that mirror real tasks (servers, routing, limits, data, tests, KV, permissions, deployment), runnable reference solutions, a self-check quiz, and a cheat sheet of the commands and APIs from the whole chapter group.

Try each exercise on paper or in your editor before opening the solution block. For the ones about Deno itself, check your answer by running it in a real Deno installation.

Deno is not available on this site, so the solutions are runnable Node 24 stand-ins that use the same web-standard APIs (Request, Response, URL, URLPattern). Each exercise says what to write in real Deno.

The exercises

1. Query parameters you can trust

Write parsePage(url) that reads page (default 1) and pageSize (default 20, maximum 100) from a URL's query string. Return { page, pageSize } or { error } when a value is not a positive integer.

2. A router with 405

Build route(method, path, handler) and a dispatcher using URLPattern. A known path with the wrong method must answer 405 with an Allow header; an unknown path 404; GET /hello/:name must greet the name from the URL.

3. A fixed-window rate limiter

Write createLimiter({ limit, windowMs, now }) returning allow(key): at most limit calls per key per window, with the clock injected so it is testable.

4. CSV to JSON

Convert CSV text with a header row into an array of objects, converting the price column to a number and respecting quoted fields containing commas.

5. Tests that catch real bugs

Write four test cases (in Deno.test style) for parsePage from exercise 1, including one for each kind of invalid input.

6. Design the KV keys

You are storing blog posts, comments (many per post) and a view counter per post. Design the key layout so that you can: (a) list a post's comments oldest first, (b) list the 10 newest posts, (c) increment views safely. Write the keys, not code.

7. Choose the permissions

A script reads ./data/*.csv, calls https://api.example.com, and writes ./out/report.json. Write the narrowest deno run command. Then say which permission is a red flag if a CSV tool asks for it.

8. Review this Dockerfile

DOCKERFILE
FROM denoland/deno:latest
COPY . .
CMD ["run", "--allow-all", "main.ts"]

List four problems and fix them.

Solutions for exercises 1 to 5

Node.js Solutions: parsePage, router, limiter, CSV, tests

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.

In real Deno, exercise 5 looks like this:

TypeScript
import { assertEquals } from "jsr:@std/assert";
import { parsePage } from "./pagination.ts";

Deno.test("defaults", () => {
  assertEquals(parsePage("http://x/"), { page: 1, pageSize: 20 });
});
Deno.test("caps pageSize at 100", () => {
  assertEquals(parsePage("http://x/?pageSize=500"), { page: 1, pageSize: 100 });
});
Deno.test("rejects bad input", () => {
  assertEquals(parsePage("http://x/?page=abc"), { error: "page must be a positive integer" });
  assertEquals(parsePage("http://x/?page=0"), { error: "page must be a positive integer" });
});

If you only tested the happy path in exercise 5, look again: the interesting bugs live in 0, negative numbers, decimals, text and huge values.

Solutions for exercises 6 to 8

6. KV keys

TEXT
["posts", createdAt, postId]        -> post          (b) kv.list({ prefix: ["posts"] }, { reverse: true, limit: 10 })
["posts_by_id", postId]              -> post key info (lookup by id)
["comments", postId, createdAt, id]  -> comment       (a) list prefix ["comments", postId], oldest first
["views", postId]                    -> KvU64         (c) kv.atomic().sum(["views", postId], 1n)

For (b), the timestamp in the key makes key order equal to age, so a reverse list with a limit returns the newest posts. Writing the post and its posts_by_id index in one atomic() commit keeps both consistent. Views use sum, never read-modify-write, so concurrent visitors cannot lose counts. See KV Basics and Atomic Operations.

7. Permissions

Terminal
deno run \
  --allow-read=./data \
  --allow-net=api.example.com \
  --allow-write=./out \
  report.ts

Each flag names exactly what the script needs. A CSV tool that asks for --allow-run (it can start any program), --allow-ffi, or an unrestricted --allow-net is a red flag, because converting a file needs none of them. If the output file is one known path, --allow-write=./out/report.json is even tighter.

8. The Dockerfile

Problems: (1) latest is not reproducible, so pin a version; (2) copying everything before installing dependencies breaks layer caching; (3) the process runs as root; (4) --allow-all removes the sandbox. A better version:

DOCKERFILE
FROM denoland/deno:2.1.4
WORKDIR /app
COPY deno.json deno.lock ./
RUN deno install --frozen
COPY . .
RUN deno cache main.ts
USER deno
EXPOSE 8000
CMD ["run", "--allow-net=0.0.0.0:8000", "--allow-env=PORT", "main.ts"]

Also add a .dockerignore and a health check; see Deploy, Compile and Docker.

Review quiz

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command checks formatting without changing files, suitable for CI?

    --check reports unformatted files and exits non-zero without rewriting anything.
  2. 2. A handler returns new Response(JSON.stringify(data)). What header is missing for a proper JSON API?

    Response.json(data) sets the content type for you; with a plain string body it defaults to text/plain.
  3. 3. Which is the safest way to count visits from many concurrent requests in Deno KV?

    sum happens inside the database and cannot lose concurrent increments.
  4. 4. A test passes locally but leaves a fetch response body unread. What does the Deno test runner do by default?

    Unconsumed bodies are open resources. Call await res.body?.cancel() or read the body.
  5. 5. Which is the best choice to run untrusted JavaScript in parallel safely?

    A worker has its own isolate and can be given no permissions at all.

Cheat sheet

Task Command or API
Run a server Deno.serve(handler) with --allow-net
Test Deno.test, deno test, --filter, --coverage
Format, lint, type-check deno fmt --check, deno lint, deno check
Tasks "tasks" in deno.json, deno task name
Add a dependency deno add jsr:@std/assert, deno add npm:zod
Database in the runtime await Deno.openKv(), kv.get/set/list/atomic
Background work kv.enqueue, kv.listenQueue, Deno.cron
Parallel work new Worker(url, { type: "module" })
Native and Wasm Deno.dlopen (--allow-ffi), WebAssembly.instantiate
Single binary deno compile --output app main.ts
Publish a library deno publish --dry-run, then deno publish

Habits that separate good Deno code from merely working code: grant the narrowest permissions, validate every input, return consistent errors, put state in a database and not in memory, test handlers as plain functions, and let the tooling (fmt, lint, check, test) run on every push.

Where to go next

  • Revisit the chapters on permissions and the standard library with the projects in mind.
  • Extend the URL shortener, the to-do API and the chat server with the ideas listed at the end of each project.
  • Read other people's Deno code on JSR and run deno doc on it.

You have reached the end of this slice of the course. Return to the Deno tutorial index any time to review a chapter.

Next: Back to the Deno tutorial