When you sent POST /tickets to your app in the last lesson, Express tried both routes, found no match, and answered with its own 404 page. That’s the request Dev’s sign-in desk will send for every visitor who walks in with a broken toaster, so the app needs a route for it.
A route that creates something has to read what the client sent, which the ticket list never had to do. In this lesson, you’ll add POST /tickets, find out what Express does with a request’s body, and answer each kind of request with the right status code. Start with the route you’d most likely write first.
Add a Route That Takes a Ticket
A new ticket needs somewhere to go. Storing it is data work with no HTTP in it, so the code belongs in tickets.ts, next to getTickets(). At the bottom of tickets.ts, add a type for the fields a visitor gives Dev and a function that turns them into a ticket:
tickets.ts
export type NewTicket = {
name: string;
item: string;
category: string;
fault: string;
};
export function addTicket(fields: NewTicket): Ticket {
const ticket: Ticket = {
id: crypto.randomUUID(),
...fields,
status: "waiting",
};
tickets.push(ticket);
return ticket;
}
The visitor doesn’t choose the id or the status, so addTicket() sets both. Node.js’s global crypto.randomUUID() returns a random ID string, and the chance that two tickets ever get the same one is negligible. Every new ticket starts out waiting. The spread syntax copies the four fields in between. For now, .push() adds the ticket to the array in memory, which is enough to try the route.
Now write the route. With node:http alone, a server has to collect a body’s chunks and parse them itself. Express hands you req with a body property, so the natural first attempt reads the fields straight from it. In app.ts, import addTicket next to getTickets, and add this route below the GET /tickets route:
app.ts
app.post("/tickets", (req, res) => {
const { name, item, category, fault } = req.body;
const ticket = addTicket({ name, item, category, fault });
res.status(201).json(ticket);
});
The app.post() call works like app.get() but handles POST requests. The handler destructures the four fields from req.body, adds the ticket, and answers. The res.status() method sets the status code and returns res, so you can chain .json() onto it. The status is 201 Created, the code for a request that made something new, and the body is the ticket, ID included.
A 201 response normally also carries a Location header with the new ticket’s URL. You’ll add this header later in the course, when tickets have their own URLs. That’s all you need about Location for now.
Save your changes and run npm run check. The check passes. Then send Rosa’s radio from your second terminal, with the header that labels the body as JSON. Before you look, predict what curl shows:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
There’s no ticket. You get a 500 Internal Server Error as an HTML page:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 1175
Date: Fri, 27 Nov 2026 01:50:21 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
...
<pre>TypeError: Cannot destructure property 'name' of
'req.body' as it is undefined.<br> at
file:///.../app.ts:17:11<br> ...</pre>
...
The app’s terminal shows the same TypeError, with a stack trace that starts at your handler. The paths will point to your own folder:
TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined.
at file:///.../app.ts:17:11
...
The body arrived, but nothing read it. Express doesn’t parse a request body by itself, so req.body is undefined, and destructuring undefined throws. Express caught the error and answered 500 for you.
Why did npm run check miss this? The type definitions from @types/express give req.body the type any, so TypeScript lets you read anything from it. You’ll fix that later in this lesson.
The body needs a parser, and Express ships one. Calling express.json() returns a middleware function, which runs on a request before your route handlers do. When a request’s Content-Type is application/json, it reads the body, parses it with JSON.parse(), and puts the result in req.body. Register it with app.use(), right after const app = express(); and before any routes:
app.ts
const app = express();
app.use(express.json());
Routes and middleware run in the order you add them, so the parser has to come first. Middleware has more uses, but that’s all you need about app.use() for now. Save, send Rosa’s radio again, and this time the ticket comes back with a new ID. From here on, curl’s long output lines are wrapped for display:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 153
ETag: W/"99-zO3/bhp9Ox0wMVlGxRW1X6toQRE"
Date: Fri, 27 Nov 2026 01:50:37 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"id":"5bd40fb7-c5f3-4c38-893f-a87b927616f2","name":"Rosa","item":"radio",
"category":"electrical","fault":"No sound from the speaker","status":"waiting"}
Now leave out the -H option. Without it, curl -d labels the body application/x-www-form-urlencoded, the format of an HTML form, and the parser skips any body that isn’t labeled as JSON. So the same 500 and the same TypeError come back:
$ curl -i \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 1173
Date: Fri, 27 Nov 2026 01:50:37 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
...
<pre>TypeError: Cannot destructure property 'name' of
'req.body' as it is undefined.<br> ...</pre>
...
So req.body stays undefined when no parser is registered, and also when the request isn’t labeled as JSON. If you read older Express code, you’ll often see app.use(bodyParser.json()) from the body-parser package doing the same job, and handlers that expect req.body to be at least {}. Express 5 leaves it undefined.
If you’d like to understand why Express leaves the body alone until you ask, the mentor can talk it through with you:
Check What the Client Sent
A client that forgets the header shouldn’t get a 500, which says the server broke. Here the request is at fault, so the answer should tell the client what to fix. The same goes for a body that’s valid JSON but has no item: Dev can’t fix an item the ticket doesn’t name.
The first step is to stop trusting any. Assign req.body to a variable of type unknown, and TypeScript won’t let you read a field until you’ve checked it’s there. You narrow unknown with the typeof and in checks you know from TypeScript. Add a function for that at the bottom of tickets.ts:
tickets.ts
export function toNewTicket(data: unknown): NewTicket | undefined {
if (typeof data !== "object" || data === null) {
return undefined;
}
if (
!("name" in data) ||
!("item" in data) ||
!("category" in data) ||
!("fault" in data)
) {
return undefined;
}
const { name, item, category, fault } = data;
if (
typeof name !== "string" ||
typeof item !== "string" ||
typeof category !== "string" ||
typeof fault !== "string"
) {
return undefined;
}
return { name, item, category, fault };
}
The toNewTicket() function returns the four fields only when the data is an object with all four as strings, and undefined otherwise. Like addTicket(), it knows nothing about HTTP. These checks are deliberately minimal. An empty item still gets through, for example. Schemas, like the Zod ones you’ve written, take over these checks later on the path. Here, checks by hand keep the focus on which status each failure gets.
Each failure gets its own status. A body that isn’t labeled as JSON gets 415 Unsupported Media Type. For the rest, the API has one rule: 400 for a body that isn’t a JSON object or array, and 422 Unprocessable Content for an object or array that breaks the ticket’s rules, such as a ticket with no item.
Valid JSON such as null gets a 400 response because express.json() rejects any value that isn’t an object or array. A missing body isn’t a JSON value at all, so it gets a 400 too. An empty body from curl -d '' behaves differently, as the optional collapse below explains.
Your route’s own error responses use the API’s error shape, so add a small helper above the routes in app.ts:
app.ts
function errorBody(code: string, message: string) {
return { error: { code, message, details: null } };
}
Then import toNewTicket next to the other two functions, and replace the POST /tickets route with this version:
app.ts
app.post("/tickets", (req, res) => {
if (req.is("application/json") === false) {
const message = "Send the body as application/json.";
res.status(415).json(errorBody("wrong_content_type", message));
return;
}
const body: unknown = req.body;
if (body === undefined) {
const message = "Send a ticket in the request body.";
res.status(400).json(errorBody("empty_body", message));
return;
}
const fields = toNewTicket(body);
if (fields === undefined) {
const message =
"Send a name, an item, a category and a fault as strings.";
res.status(422).json(errorBody("invalid_ticket", message));
return;
}
const ticket = addTicket(fields);
res.status(201).json(ticket);
});
The first check calls req.is(), which compares the request’s Content-Type with a type and returns false for a body of another type. The second catches a request with no body, which leaves req.body undefined. The handler stays thin. It checks the request, lets toNewTicket() and addTicket() do the work, and answers. Each return after an error ends the handler, so every request still gets exactly one response.
Express also has res.sendStatus(415), which sends only the status’s name as plain text, but the café’s clients expect the error shape.
Valid JSON that isn’t an object or an array, such as "radio" or null, never reaches your check, because by default express.json() answers it with its own 400. If you’d rather answer it with your 422, register the parser with express.json({ strict: false }).
A request with the JSON header and no body at all makes req.is() return null rather than false, so the empty_body check answers it with 400. But curl -d '' with the JSON header sends an empty body, which the parser turns into {}, so that gets 422.
Send the radio without the header again, and the answer now says what to change:
$ curl -i \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 415 Unsupported Media Type
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 101
ETag: W/"65-RzAEgjUmTdCCbXH5AT3oYi6GdiM"
Date: Fri, 27 Nov 2026 01:51:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":{"code":"wrong_content_type",
"message":"Send the body as application/json.","details":null}}
Then send it with the header but without the item:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 119
ETag: W/"77-0qAmh/WhHnio5+tqTRW1ahF/Avg"
Date: Fri, 27 Nov 2026 01:51:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":{"code":"invalid_ticket",
"message":"Send a name, an item, a category and a fault as strings.",
"details":null}}
Node.js prints the older name for 422, Unprocessable Entity, but clients go by the number.
A full ticket still has to get through. Each save restarted the app, clearing the radio you created earlier from memory, so send it once more:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","item":"radio","category":"electrical",
"fault":"No sound from the speaker"}' \
http://localhost:3000/tickets
HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 153
ETag: W/"99-qgLtPSc7GDEbHUhwtNGx6dbJmL4"
Date: Fri, 27 Nov 2026 02:02:43 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"id":"0e4623c3-eef7-4446-bdce-a6dca3280519","name":"Rosa","item":"radio",
"category":"electrical","fault":"No sound from the speaker","status":"waiting"}
Ask for the list, and the radio is the sixth ticket, with the ID the 201 gave it:
$ curl http://localhost:3000/tickets
[{"id":"1","name":"Priya","item":"toaster","category":"electrical",
"fault":"Only one side heats up","status":"waiting"},
{"id":"2","name":"Marcus","item":"desk lamp","category":"electrical",
"fault":"Flickers when the arm moves","status":"on-bench"},
{"id":"3","name":"Elena","item":"torn jacket","category":"textiles",
"fault":"Ripped seam under the left arm","status":"waiting"},
{"id":"4","name":"Joe","item":"wobbly stool","category":"woodwork",
"fault":"One leg is loose","status":"fixed"},
{"id":"5","name":"Aiko","item":"bike","category":"bikes",
"fault":"Chain keeps slipping","status":"waiting"},
{"id":"0e4623c3-eef7-4446-bdce-a6dca3280519","name":"Rosa","item":"radio",
"category":"electrical","fault":"No sound from the speaker","status":"waiting"}]
Now stop the app with Ctrl+C, start it again with node --watch app.ts, and ask for the list once more:
$ curl http://localhost:3000/tickets
[{"id":"1","name":"Priya","item":"toaster","category":"electrical",
"fault":"Only one side heats up","status":"waiting"},
{"id":"2","name":"Marcus","item":"desk lamp","category":"electrical",
"fault":"Flickers when the arm moves","status":"on-bench"},
{"id":"3","name":"Elena","item":"torn jacket","category":"textiles",
"fault":"Ripped seam under the left arm","status":"waiting"},
{"id":"4","name":"Joe","item":"wobbly stool","category":"woodwork",
"fault":"One leg is loose","status":"fixed"},
{"id":"5","name":"Aiko","item":"bike","category":"bikes",
"fault":"Chain keeps slipping","status":"waiting"}]
Rosa’s radio is gone. The new ticket lived only in the array in memory, and tickets.json still holds the original five. Saving tickets to the file comes later in the course.
See What express.json() Refuses
Some bodies never reach your handler, because express.json() answers them itself.
The first is a body that isn’t valid JSON at all. A trailing comma is a common slip when you type JSON by hand, so try one:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Rosa","item":"radio",}' \
http://localhost:3000/tickets
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 1079
Date: Fri, 27 Nov 2026 01:50:37 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
...
<pre>SyntaxError: Expected double-quoted property name in JSON at position 30
(line 1 column 31)<br> at JSON.parse (<anonymous>)<br>
at parse
(/.../node_modules/body-parser/lib/types/json.js:93:21)<br> ...</pre>
...
The status is right. A body that isn’t valid JSON gets a 400, as the API’s rule says, and your handler never runs. The trouble is the response body. It’s an HTML page, and it contains a stack trace: the list of function calls that led to the error, with file paths from your computer.
Express includes the stack trace unless the NODE_ENV environment variable is production. In that case, the page only says Bad Request. Either way, a real API mustn’t send this. A stack trace tells strangers how your server is built, and a program that expects JSON can’t read an HTML page. An error handler, which comes later on the learning path, replaces these pages with the error shape.
If you’d like to see this from the side of someone probing your server, ask the mentor:
The parser also limits a body’s size. By default, it reads at most 100kb and answers a bigger body with 413 Content Too Large. The response is again an HTML page, and Node.js prints the older name, Payload Too Large.
A ticket is about 150 bytes, so the default suits the café, but an option such as express.json({ limit: "10kb" }) changes it.
Now put the pieces together yourself. This route, in an app with no app.use() call yet, adds a fixer to the café’s list of volunteers:
app.post("/volunteers", (req, res) => {
res.status(201).json({ added: req.body.name });
});
Repair it so that {"name":"Amara"} sent as JSON gets a 201 with {"added":"Amara"}, a body without the JSON header gets a 415, and a JSON object or array without a string name gets a 422, both in the error shape from errorBody().
Register the parser before the route, call req.is() first, assign req.body to a variable of type unknown, and answer a missing body with 400 as the ticket route does. TypeScript then makes you check name before you read it:
app.use(express.json());
app.post("/volunteers", (req, res) => {
if (req.is("application/json") === false) {
const message = "Send the body as application/json.";
res.status(415).json(errorBody("wrong_content_type", message));
return;
}
const body: unknown = req.body;
if (body === undefined) {
const message = "Send a volunteer in the request body.";
res.status(400).json(errorBody("empty_body", message));
return;
}
if (
typeof body !== "object" ||
body === null ||
!("name" in body) ||
typeof body.name !== "string"
) {
const message = "Send the volunteer's name as a string.";
res.status(422).json(errorBody("invalid_volunteer", message));
return;
}
res.status(201).json({ added: body.name });
});
Dev’s desk can now add a ticket, refuse one it can’t use, and say why. The next lesson is the course’s first coding exercise, and it runs in your browser, not in your project. You change the file in the editor and click Run Tests, and automated tests mark each check as passed or failed. Run them early and often, and when one fails, read its message for a clue. For more room, click Full screen.
In Exercise: Open the Parts Shelf, you’ll put this lesson to work by building the routes that list the café’s shelf of spare parts and add new parts to it.