Rebuild an Endpoint in Express

Dev wants the repair café’s sign-in desk to run on a ticket API instead of a clipboard, and that API is yours to build. So far, you’ve been the client, reading whatever status and body came back. In this course, you write the server that sets both.

You’ll use Express 5, a library that handles the work every server repeats, so your code can concentrate on the API’s own decisions. In this lesson, you’ll rebuild the starting project’s one endpoint, GET /tickets, in Express and compare the two versions line by line. Then you can say exactly what Express took over and what it left to you. Start with the server you’re about to replace.

Run the Café’s Starting Server

Before you can see what Express saves you, you need the server it replaces. The course gives you that server in its starting project, so you don’t need to have written one before. To follow along, make sure you’ve called APIs with fetch(), can read a raw HTTP response, and have run TypeScript files directly with Node.

In this course, you type each lesson’s code into the starting project on your own computer and call the server with curl -i after every change, so you always see the real exchange. If your code and the lesson’s disagree, compare your version with the finished code in the course’s second download.

You’ll also work without a walkthrough. After each section, a coding exercise in your browser has you build part of an API for the café’s shelf of spare parts. The course ends with a project where you build Dev’s full ticket API from a brief.

Open a terminal in the 01-rebuild-endpoint/starting-project folder of the course’s code download, and install its development dependencies with npm:

Language: Shell
$ npm install

added 4 packages, and audited 5 packages in 684ms

found 0 vulnerabilities

The packages are TypeScript and Node’s type definitions, which only npm run check uses. The numbers and the time in your output may differ.

The project holds the café’s data in tickets.json: five tickets, each with a string id, the visitor’s name, the item, a category, a fault, and a status. The tickets.ts module reads that file once at startup and exports getTickets(), which returns the array. It knows nothing about HTTP.

The server itself is server.ts. It answers GET /tickets with every ticket and anything else with a 404:

Language: TypeScript Filename: server.ts
import { createServer } from "node:http";
import { sendError, sendJson } from "./responses.ts";
import { getTickets } from "./tickets.ts";

const PORT = 3000;

const server = createServer((req, res) => {
  const url = new URL(req.url ?? "/", "http://localhost");
  if (req.method === "GET" && url.pathname === "/tickets") {
    sendJson(res, 200, getTickets());
  } else {
    const message = `Nothing at ${req.method} ${url.pathname}.`;
    sendError(res, 404, "not_found", message);
  }
});

server.listen(PORT, () => {
  console.log(`Listening on http://localhost:${PORT}`);
});

This listener does all the routing by hand. Node’s createServer() calls it once per request. The listener parses the URL and checks the method and the path itself, and helpers from responses.ts send the answer. The sendJson() helper sets the status and the Content-Type header and calls JSON.stringify(). The sendError() helper sends a failure in the API’s one error shape, { error: { code, message, details } }.

Start the server in your first terminal:

Language: Shell
$ node server.ts
Listening on http://localhost:3000

Open a second terminal in the same folder, and ask for the tickets:

Language: Shell
$ curl -i http://localhost:3000/tickets
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Fri, 27 Nov 2026 01:28:24 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 597

[{"id":"1","name":"Priya","item":"toaster",...},...]

The body holds all five tickets on one line, shortened here. Keep this response in mind, because Express’s version should send the same tickets. Stop the server with Ctrl+C in its terminal, since your Express app will use port 3000 too.

Rebuild GET /tickets With Express

Every server you write needs the same plumbing. It parses the URL, checks the method and the path, sets the headers, turns data into text, and answers the requests nobody planned for. That’s the part Express handles. Install it in the first terminal:

Language: Shell
$ npm install express

added 65 packages, and audited 70 packages in 817ms

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Look in package.json, and you’ll find express under "dependencies", at a version starting with 5. It goes there and not under "devDependencies", because the server needs it to run. The express package has no TypeScript types of its own, so install its type definitions for npm run check too:

Language: Shell
$ npm install --save-dev @types/express

added 9 packages, and audited 79 packages in 550ms

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Without them, npm run check stops at the import with “Could not find a declaration file for module ‘express’”.

Now create app.ts next to server.ts, with the Express version of the same endpoint:

Language: TypeScript Filename: app.ts
import express from "express";
import { getTickets } from "./tickets.ts";

const PORT = 3000;

const app = express();

app.get("/tickets", (req, res) => {
  res.json(getTickets());
});

app.listen(PORT, (error) => {
  if (error) {
    throw error;
  }
  console.log(`Listening on http://localhost:${PORT}`);
});

Express’s default export is a function, and calling it in const app = express() creates an application, the object that holds your routes. A route pairs a method and a path with a handler, the function that answers the requests that match.

The app.get() call registers one route, which sends GET requests for /tickets to the arrow function. The handler receives req and res, as the listener in server.ts did. These are Node’s request and response objects with Express’s methods added.

One of these methods is res.json(), which turns the tickets into JSON text, sets Content-Type, and sends the response.

Finally, app.listen() does what createServer() and server.listen() did together. Express still calls createServer() underneath, with app itself as the listener, and returns the server it gets back. Express is a layer on top of the node:http code you’ve already seen.

One difference matters at startup. If the server can’t listen, for example because server.ts still holds port 3000, Express 5 passes that error to your callback instead of crashing. That’s why the callback checks error and throws it. Without the check, the app would print Listening on http://localhost:3000 and then quietly exit.

The button below opens a conversation with your AI mentor, prefilled with a question you can edit before you send it. Use it if you’d like to see how app.listen() connects to the node:http code it replaces:

Check the types first with the project’s check script:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

The check passes with no errors, so start the app. The --watch option makes Node restart it whenever you save app.ts or a module it imports, such as tickets.ts. It doesn’t watch tickets.json, which tickets.ts reads from disk, so restart by hand after editing the data:

Language: Shell
$ node --watch app.ts
Listening on http://localhost:3000

In your second terminal, send the same request as before:

Language: Shell
$ curl -i http://localhost:3000/tickets
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 597
ETag: W/"255-6Nrvbf0UFmPk5arXELMEeh4MaO8"
Date: Fri, 27 Nov 2026 01:28:28 GMT
Connection: keep-alive
Keep-Alive: timeout=5

[{"id":"1","name":"Priya","item":"toaster",...},...]

It’s the same 200 OK, the same Content-Type, and the same 597 bytes of tickets, from a handler with one line in it.

Express added two headers your server never sent. X-Powered-By names the framework, and the ETag is a fingerprint of the body that a client can use to ask whether anything changed. Neither changes what the ticket API does, though real deployments often switch X-Powered-By off so they don’t advertise their framework.

Compare What Express Took Over

Matching output is a good start, but you also want to know where each line of server.ts went. Put the two files side by side, and you can see what Express replaced and what’s still missing:

In server.ts In app.ts
new URL(req.url ?? "/", ...) and url.pathname === "/tickets" The path "/tickets" in app.get()
req.method === "GET" The get in app.get()
sendJson(res, 200, ...), with res.setHeader() and JSON.stringify() inside it res.json()
The else branch with sendError() Nothing yet
createServer() and server.listen() app.listen()

You can confirm that Express parses the URL for you. Ask for /tickets?status=waiting, and the route still matches, because Express compares the path without the query string, as url.pathname did. You’ll read that query string in a later lesson.

The match is looser than the handwritten test, though. By default, Express also matches /TICKETS and /tickets/, answers HEAD through the GET route, and replies to OPTIONS with the allowed methods, where server.ts sent a 404 for all of them. The two servers agree only on GET /tickets, with or without a query string.

The else branch is the interesting row. The app.ts file has no code for paths it doesn’t handle. Before you run the next command, predict how Express responds to a request for a single ticket. No route handles that request yet:

Language: Shell
$ curl -i http://localhost:3000/tickets/1
Language: Shell
$ curl -i http://localhost:3000/tickets/1
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 148
Date: Fri, 27 Nov 2026 01:28:28 GMT
Connection: keep-alive
Keep-Alive: timeout=5

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /tickets/1</pre>
</body>
</html>

When no route matches, Express answers by itself with a 404 and a small HTML page saying Cannot GET /tickets/1. That’s a sensible default for a website, but it isn’t the ticket API’s answer. The starting server sent JSON in the error shape, and a program calling the API expects that shape for every failure.

Your routes’ own 404 responses will send the error shape when you add them, and a catch-all for unknown paths comes later on the learning path. That’s all you need about Express’s fallback for now.

If you’d like to think through what that HTML page means for a client that expects JSON, the mentor can work through it with you:

Express took over the plumbing and left the decisions to you. The res.json() method sent 200 only because you didn’t ask for anything else. When Dev asks for a ticket that doesn’t exist, the status code and the error body are still yours to choose. You need to check input too. Once a later lesson adds JSON body parsing and a route that creates tickets, Express hands your handler whatever the client sent, item or not.

You can keep server.ts in the project to look back at. From here on, you’ll build on app.ts.

Check that you can explain what changed. The first question is about this branch from a node:http listener:

Language: TypeScript
if (req.method === "GET" && url.pathname === "/volunteers") {
  sendJson(res, 200, getVolunteers());
}

Answer these on paper, without changing your app.ts:

  1. How would you write that branch as an Express route?
  2. Which three jobs does res.json(getTickets()) do that sendJson() did by hand?
  3. A client sends GET /visitors to your app.ts. What status and Content-Type come back, and why isn’t that the API’s answer?
  4. Name two decisions that Express left with you.
  1. The method becomes the app method, the path becomes its first argument, and the if disappears. The route is shown below the list.
  2. It turns the data into JSON text, sets Content-Type to application/json; charset=utf-8, and sends the response with a status of 200, because you didn’t set another.
  3. You get a 404 with text/html because no route matches and Express’s fallback answers. It’s an HTML page, not JSON in the API’s error shape, so a client can’t read it like the API’s other failures.
  4. You choose which status code each outcome gets, such as a 404 for a missing ticket, and check what the client sends before using it.

The Express route from the first answer looks like this:

Language: TypeScript
app.get("/volunteers", (req, res) => {
  res.json(getVolunteers());
});

The res.json() call does what sendJson(res, 200, ...) did, with the status left at its default.

You now have an Express version of GET /tickets alongside the node:http version it replaces, and you’ve seen what Express does when no route matches. In the next lesson, Follow a Request Through Express, you’ll watch a request travel from the moment it arrives at the server to the moment it reaches your handler.

Become a Member to join the conversation.