On the server: Node.js, Deno, and Bun; a typed request handler
TaskKit's tasks vanish with a closed tab. Learn what a server, a port and a runtime are, write a typed request handler from a Request to a Response and run it on the page, check the body that comes in, and see how Node.js, Deno and Bun serve it.
TypeScript
Types
On the server: Node.js, Deno, and Bun; a typed request handler. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Your friend has been using TaskKit's React page from the last lesson
all morning. At lunch they reload the tab, and the list is empty.
In the evening they open the page on their phone: empty there too.
Every task lived in the state of one open tab, and a tab forgets
everything when it closes.
The tasks need one home: one program, running on one computer.
Every page asks it for the list and tells it about each new
task. That program is a server, and in this lesson you
write the heart of one in TypeScript. By the end you have a typed
function that answers TaskKit's requests, you have run it right
here on the page, and you know how Node.js, Deno and Bun each turn
it into a real server.
A server waits for requests
In Level 1's Module 12, TaskKit asked a weather service for a
forecast with fetch: it sent a request, and an answer came
back, a response with a status code and a body. The weather
service is a server. It is a program that starts, then waits, and
answers every request that reaches it, for as long as it runs.
A computer is reached at its network address, and many programs
on it may be waiting for requests. Each one listens (waits
for requests) on its own port, a number from 1 to 65535 that
says which program a request is for.
While you build a server, it runs on your own computer, and its
address is localhost, a name that always means "this
computer". So http://localhost:8000/tasks asks the program
listening on port 8000 of your own computer for /tasks.
Each request also names a method, a word for what it wants
done. GET asks to be sent something, as fetch asks by
default; POST sends something new, such as a task to add. Your
server reads the method and the path, /tasks, and decides what
to answer.
A browser runs a page's code, but a server is not a page. Its
code runs in a runtime: a program that runs JavaScript, and
TypeScript with its types removed, outside a browser, with access
to the network and the disk. (In "runtime error", from lesson
8.2, the word means the time the code runs; here it is the
program that runs it.) Node.js, the one you have used since
Level 1, is a runtime. Deno and Bun are two newer ones, made for
the same job.
A handler: a Request in, a Response out
The part of a server you write is the request handler: a
function the runtime calls once for each request that arrives.
It is given the request and gives back the response. In
TypeScript that is a function from a Request to a Response:
Response is the type you met with fetch, the answer a server
sends. Request is its partner: the question a client sends.
A client is the program that asks, such as a page, or fetch in
a file of yours. request.method is the method, such as "GET", and
request.url is the whole address, such as
"http://localhost:8000/tasks". Every browser and every runtime
knows these two types. Press Next step to walk through one
request, or let it play:
Page
Runtime
handle
1
Page to Runtime: GET/tasks
2
Runtime to handle: handle
All 4 steps shown.Step 1 of 4: Page → Runtime — GET /tasksStep 2 of 4: Runtime → handle — handle(request)Step 3 of 4: handle → Runtime — Response.json(tasks)Step 4 of 4: Runtime → Page — 200 OK, [{…}, {…}]
All 4 steps shown.
Your handler never touches the network: the runtime does all of that, as the
figure shows. That is why a handler can run on this page, where no server can
listen: you build the Request yourself and hand it over. Press Run:
Line by line, the new pieces:
new Request(address) builds a request, as a runtime would for
one that arrived. A request built with only an address is a
GET. Building it sends nothing anywhere.
new URL(request.url) makes a URL (Uniform Resource Locator,
the full address) from the text and splits it into its parts, and
url.pathname is the part after the port, "/tasks". The
handler compares that, because request.url holds the whole
address.
Response.json(tasks) builds a response whose body is tasks
written as JSON (JavaScript Object Notation, values written as
text, lesson 12.1), with the status 200 and a header, a line of
information sent ahead of the body, that says the body is JSON.
new Response("Not found", { status: 404 }) builds one with a
text body and the status you give it.
await tasksAnswer.text() reads the body as text, as
response.json() read it as JSON in Level 1. Reading a body
takes an await here as it did there.
Each if that answers one method and path is a route: this
handler has one route, GET /tasks, and answers everything else
with 404. The type does its work on both sides. Response as the return
type means every path through the function must end with a
response, and the check stops one that does not (the common
mistake below). Request as the parameter means the handler can
read only what a request has: request.titel fails the check
with Property 'titel' does not exist on type 'Request'.
Node.js, Deno and Bun
All three runtimes run TypeScript files and can listen on a port.
Deno and Bun serve a function from a Request to a Response
directly, so handle is all they need. Node.js is older than the
Request type, and its own server, from the node:http module,
calls a function of another shape:
Deno
Does: Calls handle with a Request, sends its Response
Never: Opens the network unless you allow it
Bun
Does: Calls handle as its fetch, with a Request
Never: Takes handle alone: it goes under fetch
Node.js
Does: Calls your function with Node's own request and response
Never: Takes a handle that returns a Response
Deno and Bun call your handle as it is; Node's own server
calls a function of another shape
Deno comes from Ryan Dahl, who also made Node.js, and was
written to fix what he thought Node got wrong. It reads
TypeScript with no setup and comes with the types of its own
Deno functions, so deno check needs no @types package. It is
secure by default: a program may not use the network or the
disk until you allow it. --allow-net allows the network.
Deno.serve listens on port 8000 unless you name another.
Bun is built for speed: it starts quickly, and installs
packages and runs tests with tools of its own. It also reads
TypeScript with no setup, and takes a handler under the name
fetch. This fetch is not the one you call: it is the name
other web servers also give the function that answers requests.
Node.js is the oldest of the three, from 2009, and npm (the
Node package manager, the tool that installs packages) was made
for it; Deno and Bun install most npm packages too. The function
you give createServer gets two objects: request, whose url
is only the path, "/tasks", and response, an object your
function writes the answer into with response.end(…), instead of
returning one. A library can let Node serve a handle like yours
too: Hono is one, and Bonus B gives it a lesson of its own,
Hono: a small server for any runtime, with typed routes.
What none of the three does is check your types when it runs a file: Level 1's
rule, TypeScript checks and the runtime runs, holds on every runtime. Node and
Bun remove the types and run what is left. Deno does the same with deno run,
and checks them only when you ask:
Runtime
Runs a .ts file
Checks its types
Node.js
node server.ts
tsc --noEmit, with @types/node
Deno
deno run --allow-net server.ts
deno check server.ts
Bun
bun server.ts
tsc --noEmit, @types/bun, "bun" in types
For Bun, types is the tsconfig.json setting from lesson 9.3:
@types/bun loads only when "bun" is listed there. A tsc check
needs a folder set up as TaskKit is: a package.json with
"type": "module", TypeScript and @types/bun installed with
npm install --save-dev, and a copy of TaskKit's tsconfig.json
with "types": ["bun"]. deno check needs none of that.
Your handler as a real server
On the page, you call handle yourself. To have a runtime call
it, the server gets a folder of its own, beside TaskKit rather
than inside it: TaskKit's tsconfig.json describes Node alone
("lib": ["es2023"], lesson A1.1), so its check would not know
Deno or Bun. This is a step for your own terminal:
Make ~/projects/taskkit-server, beside TaskKit.
Put the first handle.ts of this lesson in it, the one with
two tasks, with export in front of function handle.
Install Deno or Bun: npm install -g deno or
npm install -g bun works on every system (-g installs a
command for the whole computer rather than one project);
deno.com and bun.com list other ways.
Write server.ts beside handle.ts, for your runtime:
Start it with the runtime's command from the table, here Deno's:
That is Deno 2's line. The terminal now stays busy: the server is
waiting, and the prompt does not come back. On macOS and Linux
Deno also names 0.0.0.0, which means it listens on every network
address the computer has, localhost among them; on Windows it
prints localhost alone. With Bun 1, bun server.ts prints
Listening on http://localhost:8000/ from its console.log.
Open http://localhost:8000/tasks in your browser to see the
tasks as JSON, or ask from a second terminal with a client.ts
of the Level 1 kind:
To stop the server, go back to its terminal and press:
⌃ Control+C
Ctrl+C
Ctrl+C
A body arrives as unknown
Reading the list is half of TaskKit. To add a task, the page sends
a POST request with the new task in its body, as JSON text.
The handler reads it with await request.json(), which makes the
handler async: it now returns a Promise<Response>, and every
runtime waits for that promise.
What arrives is outside data, like the weather service's answer in Level 1's
Module 12. Anyone can send your server anything: text that is not JSON, a task
with no title, a title that is a number. So the handler keeps the body in a
box typed unknown, as Module 12 kept the forecast, and asks it questions at
the edge before a task is made from it. (With @types/node and no dom in
lib, as in TaskKit since lesson A1.1, request.json() already gives an
unknown; with Deno's and Bun's types it gives an any, and the unknown
box keeps that any from spreading.) Each question that fails is answered
with 400 Bad Request and a sentence that says why. A request that adds
something is answered with 201 Created when it works.
Pick a body with the switch, press Next step to walk it
through the questions, or let it play:
request.json(): passes✓Is the text JSON?
body: passes✓An object with title?
body.title: passes✓Is title a string?
Response: reached201 Added: Pay rent
Each question stops a body that lacks what it asks for,
with a 400 that says why
All 7 steps shown.Step 1 of 7: request.json()Step 2 of 7: request.json(): passesStep 3 of 7: bodyStep 4 of 7: body: passesStep 5 of 7: body.titleStep 6 of 7: body.title: passesStep 7 of 7: Response
All 7 steps shown.
request.json(): stops here✕Is the text JSON?
body: never reachedAn object with title?
body.title: never reachedIs title a string?
Response: never reached201 Added: Pay rent
request.json() stops here400 The body is not JSON
Each question stops a body that lacks what it asks for,
with a 400 that says why
All 2 steps shown.Step 1 of 2: request.json()Step 2 of 2: request.json(): stops here. 400 The body is not JSON
All 2 steps shown.
request.json(): passes✓Is the text JSON?
body: passes✓An object with title?
body.title: stops here✕Is title a string?
Response: never reached201 Added: Pay rent
body.title stops here400 A task needs a title
Each question stops a body that lacks what it asks for,
with a 400 that says why
All 6 steps shown.Step 1 of 6: request.json()Step 2 of 6: request.json(): passesStep 3 of 6: bodyStep 4 of 6: body: passesStep 5 of 6: body.titleStep 6 of 6: body.title: stops here. 400 A task needs a title
All 6 steps shown.
Here is TaskKit's whole handle.ts, with the list's route first
and the questions after it. request.json() throws a SyntaxError
on text that is not JSON, so try and catch turn that into a
400. The last if holds the questions from Level 1's Module 12: an
object, not null, with a title, which is a string. Press
Run:
The second argument of new Request sets what a browser would
send: the method and the body. JSON.stringify writes the task
as JSON text, as TaskKit's page will. Only the first request adds
a task, so the list ends with two. The list lives in the server's
memory, so it lasts while the server runs and starts again from
Buy milk when it restarts; saving it with Module 12's
writeFile after each change is how it would survive one.
Inside the last if, the questions narrow body step by step, as
in Module 12, until body.title is a string. Leave one question
out and the line that reads it fails: without typeof body.title !== "string", the task's title is unknown, and the check says
Type 'unknown' is not assignable to type 'string'.
Predict before you run
Predict
What status does this request get back from the handler above?
The common mistake: a request with no answer
A handler grows one if at a time: a route for the list, then
one for the count. It is easy to write the routes you thought
of and forget the requests nobody planned for. Run this:
Common mistake
A handler whose last request gets no Response
A request for any other path, /notes or a typo, reaches the end
of the function, and nothing is returned there. The return type
says every request gets a Response, so the check refuses it with
TS2366, lesson 5.1's error for a function with a way out that
has no return.
Function lacks ending return statement and return type does not include 'undefined'.
The fix
End the handler with the answer for everything else: 404 Not found. Now every path through it returns a Response.
Without : Response on the handler, TypeScript gives it the type
Response | undefined. The check still fails, but far from the
mistake: on the Deno.serve or Bun.serve line, in a long error
that never names the missing return: Deno's says no overload
matches (none of the forms Deno.serve accepts fits your
function), Bun's says a websocket property is missing.
And since deno run and bun never check, a
skipped check lets the mistake reach the runtime, where it shows
only when the forgotten request arrives. Deno answers 500 Internal Server Error, the status for a server that failed, and
prints TypeError: Return value from serve handler must be a response or a promise resolving to a response; Bun prints error: Expected a Response object, but received 'undefined'. Write the
return type on every handler, and the check points at the
handler's own line before any request arrives.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each check builds a Request, hands it to your handle and reads
the Response it returns, as a runtime would. Press Run to try
the code, and Check when you think it works.
Recap
Recap · 3 questions
Check yourself
What does a runtime do for your request handler?
Check yourself
Why is a handler typed (request: Request): Response?
Check yourself
What should a handler do with a body that fails a question?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
On the server: Node.js, Deno and Bun
What things are
Word
What it means
Server
A program that waits for requests and answers them
Port
The number that says which program a request is for
localhost
This computer, as an address
Method
What a request wants: GET to get, POST to add
Runtime
Runs your code outside a browser: Node.js, Deno, Bun
Request handler
A function from a Request to a Response
Body
The data a request carries too, not only a response
Route
One if that answers one method and path
Client
The program that sends a request
Code
Write
To
(request: Request)
Type a handler; it returns a Response
request.method
Read the method: "GET", "POST"
url.pathname
The path in new URL(request.url): "/tasks"
Response.json(tasks)
Answer 200 with JSON
new Response(text, …)
Answer with text; { status: 404 } sets it
let body: unknown
Keep the body until it is questioned
await request.json()
Read the body as JSON
await response.text()
Read a body as text
new Request(url, { … })
Build a request: its method and body
Where to go next
You can now say what a server and a runtime are, write a typed
handler that answers GET and POST requests and questions what
comes in, and say how Node.js, Deno and Bun each run it. A real
server adds more routes, a database and logins, and each of
those is called from a handler like this one.
Next is Full-stack: sharing types between client and server.
The page keeps each task as a string, and the server keeps it as
a Task object. That lesson gives both sides one Task type, so
a change on one side fails the check on the other.
Before you move on, press Edit on the first handler of this
lesson and make its 404 name the path it could not find, No such path: /notes, using url.pathname in a template string. Predict
what /tasks/ with a slash at the end gets back, then run it.
(request)
3
handle to Runtime: Response.json(tasks)
4
Runtime to Page: 200OK,[{…},{…}]
The runtime turns the request into a Request, and your
handler turns it into a Response
Deno.serve(handle)
Serve it with Deno, on port 8000
Bun.serve({ … })
Serve it with Bun: port, fetch: handle
deno run --allow-net
Start Deno's server: add the file's name
bun server.ts
Start Bun's server
How it runs
Rule
What it means
Return a Response on every path
End with a 404 for the rest
Question the body at the edge
A failed question answers 400
201, 400, 404
Created, bad request, not found
No runtime checks types
tsc --noEmit or deno check does
Exercise · Read the code
Read which runtime checks your types
bash
node server.tsdeno run --allow-net server.tsbun server.ts
server.ts has a type error on one of its lines. Which of these
three commands stops before the server starts?
interface Task { title: string; done: boolean;}const tasks: Task[] = [{ title: "Buy milk", done: false }];async function handle(request: Request): Promise<Response> { const url = new URL(request.url); if (request.method === "GET" && url.pathname === "/tasks") { return Response.json(tasks); } if (request.method !== "POST" || url.pathname !== "/tasks") { return new Response("Not found", { status: 404 }); } let body: unknown; try { body = await request.json(); } catch (error) { return new Response("The body is not JSON", { status: 400 }); } if ( typeof body !== "object" || body === null || !("title" in body) || typeof body.title !== "string" ) { return new Response("A task needs a title", { status: 400 }); } tasks.push({ title: body.title, done: false }); return new Response(`Added: ${body.title}`, { status: 201 });}async function send(text: string): Promise<void> { const response = await handle( new Request("http://localhost:8000/tasks", { method: "POST", body: text, }), ); console.log(response.status, await response.text());}await send(JSON.stringify({ title: "Pay rent" }));await send("Pay rent");await send(JSON.stringify({ title: 5 }));console.log(tasks.length);
ts
await send(JSON.stringify({ name: "Pay rent" }));
ts
function handle(request: Request): Response { const url = new URL(request.url); if (url.pathname === "/tasks") { return Response.json(["Buy milk", "Call Mom"]); } if (url.pathname === "/tasks/count") { return Response.json({ count: 2 }); }}const response = handle(new Request("http://localhost:8000/notes"));console.log(response.status);
ts
function handle(request: Request): Response { const url = new URL(request.url); if (url.pathname === "/tasks") { return Response.json(["Buy milk", "Call Mom"]); } if (url.pathname === "/tasks/count") { return Response.json({ count: 2 }); } return new Response("Not found", { status: 404 });}const response = handle(new Request("http://localhost:8000/notes"));console.log(response.status);
Exercise · Write the code
Answer GET /tasks/done with the tasks that are done
Add a route: GET /tasks/done answers with only the tasks whose
done is true, as JSON. The list and the 404 keep working.
Loading the editor…
Exercise · Fix the error
Make GET /tasks find its route
TypeScript finds nothing wrong with this handler, yet every
request gets 404, /tasks too. Find out why, and fix it.
Loading the editor…
Exercise · Write the code
Refuse a task whose title is empty
{ "title": "" } passes every question in the handler's last if and
adds a task with no title. Make the handler answer it with 400
and A task needs a title, as it answers a missing title.
Loading the editor…
import { handle } from "./handle.ts";Deno.serve(handle);
import { handle } from "./handle.ts";const server = Bun.serve({ port: 8000, fetch: handle });console.log(`Listening on ${server.url}`);