A college fest site takes food orders from a few hundred phones at once. Each order has to be stored somewhere that survives a restart, and the server that takes it has to stay readable as routes pile up.
The web server chapter built a server by hand on node:http. You parsed the URL, matched a method and a path, collected body chunks and mapped every failure to a status code yourself. That is a good way to learn HTTP, and a tiring way to write twenty routes. Express is a small framework on top of node:http that does the repeated parts. It matches routes, runs a chain of functions on each request, parses JSON bodies and turns errors into responses.
This chapter uses Express 5.3.0, installed with npm install express. Express 5 is the version where rejected promises reach your error handler on their own, and that one change shapes how the code below looks.
Routes and middleware
A route pairs an HTTP method and a path pattern with a handler function: app.get('/menu/:id', handler). The :id part is a route parameter, and Express puts its value in req.params.id as a string.
A middleware is a function with the signature (req, res, next). Express keeps the functions you register in order and runs them one after another for each request. A middleware can do four things: change req or res, end the response, call next() to pass control to the next function, or call next(err) to jump to error handling. A route handler is simply the last middleware in the chain for that path.
Three pieces of Express are used in almost every API. express.json() is a built-in middleware that reads the body when the Content-Type is JSON and stores the parsed value in req.body. express.Router() creates a small group of routes that you mount under a prefix with app.use('/menu', router), so the router's own paths are relative to that prefix. An error-handling middleware has four parameters, (err, req, res, next), and Express treats a function with four parameters as an error handler. The Express guide says to define it last, after all other app.use() and route calls.
What Express 5 changed for async code
Database calls are asynchronous, so nearly every handler in this chapter is an async function. In Express 4 you had to catch the error yourself and call next(err), so every async handler needed a try/catch. The Express 5 migration guide says that handlers returning rejected promises are now handled by forwarding the rejected value to the error-handling middleware, as if you had called next(err). You can throw in an async handler and let the error handler answer.
The same guide notes that req.body is undefined when no body parser has run on that request. In Express 4 it was {}. Always check that req.body exists before you read from it.
A small app you can run
The app below has a logger middleware, express.json(), a router with an async route that fails, an echo route, and an error handler. The logger waits for the response's finish event and then prints the method, the full URL and the status. It reads req.originalUrl, which keeps the path as the client sent it, /menu/7, instead of the path relative to the router.
The error handler uses err.status ?? 500. Errors made by the JSON parser carry a status of 400, and a plain Error has none. The script l1-run.sh starts the app on port 55651 and sends six requests with curl.
text
[{"id":1,"name":"cold coffee"},{"id":2,"name":"veg puff"}] [200]
{"id":7} [200]
{"error":"menu service is down"} [500]
{"body":{"a":1}} [200]
{"body":null} [200]
{"error":"Unexpected end of JSON input"} [400]
Express 5.3.0 on Node 24.18.0. Each line ends with the status code in brackets.
text
GET /menu 200
GET /menu/7200
GET /menu/boom/async 500
POST /echo 200
POST /echo 200
POST /echo 400
What the logger middleware printed, in the same order.
Read the third response first. The route threw after an await, no try or catch caught it, and the client still received a clean 500 with the message from our handler. That is the Express 5 behaviour. The last response shows the other side: broken JSON never reached the route, because express.json() failed first and the error handler turned its 400 into a response. The echo route printed null for the request with no body, which is what req.body ?? null gives when req.body is undefined.
Why does an async route handler that throws still produce a response in Express 5?
Express 5 forwards the rejected promise to the error-handling middleware, as if the handler had called next(err). In Express 4 the handler had to catch the error and call next(err) itself.
What marks a function as an error-handling middleware, and where should it be registered?
It has four parameters, (err, req, res, next). Register it after all other app.use() and route calls so errors from them reach it.
A route reads req.body.name and the client sent no body. What happens in Express 5?
req.body is undefined when no body was parsed, so the read throws a TypeError. Check req.body first, or validate it before use.
Part 2 · Connecting to PostgreSQL
A database is another program
An API that keeps orders in a JavaScript array loses them at the next restart. A database server is a separate program that stores data on disk and answers queries from many clients at once. PostgreSQL, usually called Postgres, is an open-source relational database: it stores rows in tables, and you ask for them with SQL.
Your Node process is a client. It opens a network connection, sends SQL text, and receives rows. Opening a connection is slow compared with running a small query, because the server and driver must set up the session first. The driver used in this chapter is pg, also called node-postgres, version 8.23.1. It speaks the Postgres wire protocol, so it works with any server that speaks it.
The lab database
There is no Postgres install on the machine used for this course, and no container tool. The lab runs PGlite 0.5.15 instead. PGlite is real PostgreSQL 18.6 compiled to WebAssembly and run inside a Node process. The @electric-sql/pglite-socket package, version 0.2.18, puts it on a TCP port so that pg can connect like it would to any server. This is a teaching setup and not a production one. Everything you write against pg below works the same against a normal Postgres server.
js
import { PGlite } from'@electric-sql/pglite';
import { PGLiteSocketServer } from'@electric-sql/pglite-socket';
const db = await PGlite.create();
const server = new PGLiteSocketServer({
db,
port: 55650,
host: '127.0.0.1',
maxConnections: 8,
});
await server.start();
console.log('lab database on 127.0.0.1:55650');
Two notes about this setup. The maxConnections option defaults to 1 in this package. With that default, a second connection from a pool was reset with ECONNRESET in a test run, so the lab passes 8. The package README also says it multiplexes several connections onto one database instance, which a normal server does not do. So the lab can show how a pool queues work, but it cannot show lock waits or deadlocks, and this chapter does not try to. Those are described from the Postgres documentation where they come up.
Client and Pool
A pg.Client is one connection. You call connect(), run queries, and call end(). A pg.Pool is a set of connections that your code borrows from and returns. pool.query(text, values) borrows an idle connection, runs the query, and gives it back. pool.connect() hands you a client to keep for several statements, and you give it back with client.release().
The next script connects both ways and prints the pool's default settings. The pool the app uses is created once, in its own file.
pg 8.23.1 against the lab server. The first line is cut at the first comma.
After the one pool.query, the pool held one connection, and it was idle. The pool's defaults, from the run, are max: 10 and idleTimeoutMillis: 10000. The node-postgres documentation adds that connectionTimeoutMillis defaults to 0, which means a request waits for a connection without a limit. The app pool in this chapter sets max: 4 so that waiting is easy to see, and connectionTimeoutMillis: 2000 so that a request waits at most two seconds for a connection and then fails. The reason for that limit comes in the transactions lesson.
Why use a pool
Each connection takes resources on the database server. PostgreSQL limits the total with max_connections, whose default the documentation gives as typically 100. If every request opened its own connection, a traffic spike would hit that limit and fail. A pool fixes the number of connections, so the database sees steady load, and requests beyond that number wait in line inside your process. The sum of max over all your Node instances must stay below the server's max_connections, with room left for other tools.
The script below starts ten requests at once. Each one borrows a connection, holds it for 100 ms as a stand-in for a query, and releases it.
right after start: { total: 4, idle: 0, waiting: 6 }
request 1 got a connection at ~10 ms
request 2 got a connection at ~10 ms
request 3 got a connection at ~10 ms
request 4 got a connection at ~10 ms
request 5 got a connection at ~120 ms
request 6 got a connection at ~120 ms
request 7 got a connection at ~120 ms
request 8 got a connection at ~120 ms
request 9 got a connection at ~230 ms
request 10 got a connection at ~230 ms
Pool of 4 on this machine. Times are rounded to 10 ms and vary a little on each run.
Directly after the ten calls started, the pool had created four connections, none idle, and six requests were waiting. Four requests got a connection within the first 10 ms, the next four after about 110 to 120 ms, and the last two after about 220 to 230 ms (the range is from five runs). Waiting is the pool doing its job. The scene shows the same picture.
Animated sceneTen requests, a pool of four connections0:16
Watch for the pool's queue: only four connections exist
Read it as steps
Four requests hold a connection at once. The other six wait in the pool's queue and go in waves.
A pool too small makes requests wait for no reason, and a pool too large pushes the work onto the database. Start near the number of queries the database can truly run at once, then measure.
Why does an API use a pool instead of opening a connection per request?
Connecting is slow and every connection takes server resources. A pool reuses a fixed number of connections and makes extra requests wait, so a spike cannot exhaust the server's max_connections.
A pool has max: 4 and ten requests ask for a connection at once. What happens to six of them?
They wait in a first-in, first-out queue inside the pool and each gets a connection as another request releases one. In the run, pool.waitingCount was 6 right after the ten calls.
What default does pg.Pool use for max, and what does the connection timeout default to?
max is 10 and idleTimeoutMillis is 10000. connectionTimeoutMillis defaults to 0, which means no limit on the wait.
Part 3 · Parameterised queries
Data that becomes code
A search box takes a name and the server looks up orders for that customer. If the server builds the SQL by joining strings, a visitor can type text that the database reads as part of the query. This attack is called SQL injection.
The cause is simple. SQL text mixes commands and data. When you paste user input into the text, the database cannot tell which part you meant as a value. A parameterised query keeps them apart: the statement contains numbered placeholders such as $1, and the values travel separately. The node-postgres documentation says to keep the parameters apart from the query text and warns against concatenating them into it.
String building against placeholders
The orders table from the lab has three rows, for Asha, Ravi and Meena. The script below searches for a customer named x' or '1'='1, first by building the SQL string, then with a placeholder, and then with an honest name.
js
import { pool } from'./pool.mjs';
const typed = "x' or '1'='1";
const sql =
`select ref, customer from orders where customer = '${typed}'`;
console.log('built SQL:');
console.log(' ', sql);
const bad = await pool.query(sql);
console.log('string-built rows:', bad.rowCount);
const good = await pool.query(
'select ref, customer from orders where customer = $1',
[typed],
);
console.log('parameterised rows:', good.rowCount);
const ok = await pool.query(
'select ref, customer from orders where customer = $1',
['Asha'],
);
console.log('rows:', ok.rows, 'rowCount:', ok.rowCount);
await pool.end();
text
built SQL:
select ref, customer from orders where customer = 'x' or '1'='1'
string-built rows: 3
parameterised rows: 0
rows: [ { ref: 'FEST-1001', customer: 'Asha' } ] rowCount: 1
Node 24.18.0 against the lab database.
The string-built query turned into where customer = 'x' or '1'='1'. The condition after or is always true, so all three rows came back. The same text passed as $1 matched nobody, because it was compared as a whole value against each name. The honest name returned one row.
Two details from the last line. rows is an array of objects keyed by column name. rowCount is the number of rows the command returned or changed. You will see rowCount again for updates and deletes, where it tells you whether anything matched.
A list of values
Sometimes the number of values is not fixed: all orders for a few named customers, or a batch of ids. Do not build a long or chain or glue the names into the SQL. Pass a JavaScript array as one parameter and compare with any. The driver turns the array into a Postgres array, and the whole list is still one value.
js
import { pool } from'./pool.mjs';
const names = ['Asha', 'Meena', 'Nobody'];
const { rows } = await pool.query(
`select ref, customer from orders
where customer = any($1) order by id`,
[names],
);
console.log(rows);
await pool.end();
Node 24.18.0. One name in the list matches nobody, so two rows return.
The third name, Nobody, has no orders and simply adds nothing. The same idea works for insert: a statement with several values groups, like the setup script's, has one placeholder per value. For very large batches the usual tool is copy, which is outside this chapter.
What placeholders cannot do
A placeholder stands for a value. It cannot stand for a table name, a column name or an ORDER BY direction: the documentation says Postgres does not support parameters for identifiers. If a route lets a client choose a sort column, keep a fixed list of allowed names in your code and insert only a name from that list.
Placeholders also change what the driver allows. With no values, a string holding two statements is a valid simple query. Once values are attached, pg uses the extended query protocol, where a statement is prepared on its own, and Postgres refuses to prepare two commands at once.
js
import { pool } from'./pool.mjs';
const plain = await pool.query('select 1 as a; select 2 as b');
console.log('no values:', plain.length, 'result sets');
try {
await pool.query('select $1::int as a; select 2 as b', [1]);
} catch (err) {
console.log('with values:', err.message);
}
await pool.end();
text
no values: 2 result sets
with values: cannot insert multiple commands into a prepared statement
Node 24.18.0. The first call has no values, the second has one.
This is a side effect and not the defence. The defence is that values never become SQL text. Use $1 for every value that comes from outside your code, including values that look harmless like an id from the URL.
Postgres converts text to the column's type on its own, so where id = $1 works when you pass the string '6'. The check on the id still belongs in your code, as the next lesson shows, so that a bad id returns a 400 and never reaches the database.
In one sentence, why does a placeholder stop SQL injection?
The value is sent separately from the statement text, so the database never parses it as SQL, whatever characters it holds.
A route needs ORDER BY on a column the client names. Can you pass the column as $1?
No, Postgres does not accept parameters for identifiers. Check the name against a fixed list in code and put only a listed name into the SQL.
What does rowCount tell you after delete from orders where id = $1?
The number of rows deleted. A rowCount of 0 means no row matched, so the route can answer 404.
Part 4 · The REST resource
Resources, methods and status codes
REST is a style for HTTP APIs in which the URL names a thing, called a resource, and the method says what to do with it. In this API the resource is an order: /orders is the collection and /orders/7 is one order. The method carries the verb: POST creates, GET reads, PATCH changes some fields, DELETE removes. The status code reports the result, and a client should be able to act on it without reading the body.
Request
Success
Failure
POST /orders
201 Created, with a Location header
400 for a bad body
GET /orders/:id
200 with the order
400 bad id, 404 not found
PATCH /orders/:id
200 with the updated order
400, 404
DELETE /orders/:id
204 with no body
400, 404
A 201 response says a new resource exists, and the Location header gives its URL. A 204 says the request worked and there is nothing to send back. Using 404 for an id that does not exist and 400 for one that is not even a number tells a client which of its two mistakes to fix.
The code
The router is a function that receives the pool, so a test can hand it a different one. Each handler follows the same four steps: read and check the input, run one parameterised query, look at the result, and send the response. Checking lives in a separate file, so the handlers stay short.
js
import { HttpError } from'./errors.mjs';
exportfunction parseId(text) {
if (!/^[1-9][0-9]{0,15}$/.test(text)) {
thrownew HttpError(400, 'id must be a positive whole number');
}
return text;
}
exportfunction parseNewOrder(body) {
if (body === null || typeof body !== 'object') {
thrownew HttpError(400, 'send a JSON object');
}
const { ref, customer, item, qty } = body;
const texts = { ref, customer, item };
for (const [name, v] of Object.entries(texts)) {
if (typeof v !== 'string' || v.trim() === '' || v.length > 60) {
thrownew HttpError(400, `${name} must be 1 to 60 characters`);
}
}
if (!Number.isInteger(qty) || qty < 1 || qty > 100) {
thrownew HttpError(400, 'qty must be a whole number, 1 to 100');
}
return { ref, customer, item, qty };
}
parseId accepts only digits without a leading zero, up to sixteen of them. It returns the text, and Postgres converts it. The class HttpError carries a status, and the error handler prints the message only when the status is below 500, so the client never sees a database message by accident. Now the routes.
router.patch('/:id', async (req, res) => {
const id = parseId(req.params.id);
const status = req.body?.status;
if (!['placed', 'preparing', 'delivered'].includes(status)) {
thrownew HttpError(400, 'status must be a known status');
}
const { rows } = await pool.query(
`update orders set status = $1 where id = $2
returning ${COLUMNS}`,
[status, id],
);
if (rows.length === 0) thrownew HttpError(404, 'order not found');
res.json(rows[0]);
});
router.delete('/:id', async (req, res) => {
const id = parseId(req.params.id);
const { rowCount } = await pool.query(
'delete from orders where id = $1', [id]);
if (rowCount === 0) thrownew HttpError(404, 'order not found');
res.status(204).end();
});
return router;
}
Two SQL details matter here. returning makes insert and update give back the stored row, so you need no second query, and it includes values the database made, like the new id. The PostgreSQL documentation says it returns values based on each row actually inserted or updated. And the id column is a bigint, which pg returns as a string, since a JavaScript number cannot hold every 64-bit integer. You will see "id": "7" in the output, not 7.
Calling it with curl
The script l4-run.sh starts the app on port 55651 and sends eight requests. It prints the status line and the headers that matter, and the body.
The first request returned 201 and a Location header with the order's URL. The script reads that id from the header and uses it for the rest. The numbers in the output are from the run.
text
== missing id
HTTP/1.1404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "order not found"
}
text
== bad id
HTTP/1.1400 Bad Request
Content-Type: application/json; charset=utf-8
{
"error": "id must be a positive whole number"
}
text
== qty 0
HTTP/1.1400 Bad Request
Content-Type: application/json; charset=utf-8
{
"error": "qty must be a whole number, 1 to 100"
}
An id that is a valid number but matches no row is a 404. An id that is not a number never reaches the database. The qty of 0 failed our check and returned a 400 with the reason, which the client can show to a user.
== delete again
HTTP/1.1404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "order not found"
}
The update returned the whole changed row. The first delete returned 204 with no body, and the second delete returned 404, since the order was gone. Many APIs make the second delete a 204 as well, which treats the request as already satisfied. Pick one rule and keep it for the whole API. RFC 9110 defines a method as idempotent when the intended effect of several identical requests is the same as the effect of one, and lists PUT, DELETE and the safe methods as idempotent. The second delete changed nothing on the server, so it fits, even though its response differs from the first. POST is not on that list, and it matters later: a client that retries a POST after a timeout may create two orders.
Which status and header tell a client that POST /orders created something and where to find it?
201 Created with a Location header holding the new order's URL, here /orders/<id>.
Why does returning help in an insert?
It returns the stored row, including values the database generated such as the id, so the handler needs no second query.
The API returned "id": "7" as a string. Why?
The column is a bigint. The pg driver returns bigint values as strings, because a JavaScript number cannot hold all 64-bit integers exactly.
Part 5 · Transactions
All or nothing
Moving 10,000 paise from one wallet to another takes two updates: subtract from one balance and add to the other. If the server stops between them, money has disappeared. A transaction groups statements into one all-or-nothing unit. The PostgreSQL tutorial describes it exactly that way: either all the updates happen or none do, and other sessions see the work as having happened completely or not at all.
You open a transaction with BEGIN. COMMIT makes every change permanent. ROLLBACK throws all of them away. When a statement inside the transaction fails, you send ROLLBACK and the earlier statements in that transaction leave no trace.
One connection for the whole transaction
A transaction belongs to a single connection. With a pool, pool.query() may use a different connection each time, so BEGIN on one and the update on another would not be a transaction at all. The node-postgres documentation is direct about it: do not use transactions with pool.query, and use one client for every statement. So the code checks a client out with pool.connect(), runs BEGIN, the work and COMMIT on it, sends ROLLBACK in a catch, and calls release() in a finally so that the connection always goes back.
The lab table wallets has a check that the balance is never negative. The helper move subtracts, then adds, and throws if the second update changed no row. It takes either the pool or a client, so the same function can run with or without a transaction.
js
asyncfunction move(db, from, to, paise) {
await db.query(
`update wallets set balance_paise = balance_paise - $1
where id = $2`,
[paise, from]);
const credit = await db.query(
`update wallets set balance_paise = balance_paise + $1
where id = $2`,
[paise, to]);
if (credit.rowCount === 0) thrownew Error(`no wallet ${to}`);
}
exportasyncfunction plainTransfer(from, to, paise) {
await move(pool, from, to, paise);
}
plainTransfer calls move on the pool, so each update is its own transaction. transfer wraps move in BEGIN and COMMIT. The script runs both with a missing wallet, then runs an overdraft, then a good transfer.
start { asha: 50000, ravi: 20000 }
no transaction: failed with "no wallet nobody"
after no transaction { asha: 40000, ravi: 20000 }
transaction: failed with "no wallet nobody"
after transaction { asha: 50000, ravi: 20000 }
overdraft: 23514 wallets_balance_paise_check
after overdraft { asha: 50000, ravi: 20000 }
after good transfer { asha: 35000, ravi: 35000 }
Node 24.18.0. Amounts are in paise. Wallets start at 50000 and 20000.
Without a transaction, asha lost 10,000 paise and nobody got it: the debit was already committed when the credit failed. With the transaction, both wallets are as they were. The overdraft case shows a different failure, a database error with code 23514, a check violation on the balance. The catch rolled back, and nothing changed. The good transfer moved 15,000 paise and both balances moved.
Animated sceneA transfer fails after the debit and rolls back0:18
Watch for the debit being undone when the credit fails
Read it as steps
The debit ran, the credit found no wallet, so ROLLBACK cancels the debit as well.
The scene is the same failure in time order. The debit looks done from inside the transaction, but it is not committed, and the ROLLBACK removes it.
Always release
A checked-out client that is never released stays taken, and the pool shrinks by one for good. The node-postgres documentation says every checked-out client must be released, or later connect calls time out or hang. The script below sets max: 2 and a 500 ms connection timeout, then takes three clients without releasing any.
js
import pg from'pg';
const pool = new pg.Pool({
host: '127.0.0.1', port: 55650, user: 'postgres',
max: 2, connectionTimeoutMillis: 500,
});
for (let n = 1; n <= 3; n++) {
try {
const client = await pool.connect();
console.log(`request ${n}: got a client, never released it`);
void client;
} catch (err) {
console.log(`request ${n}: ${err.message}`);
}
}
console.log({ total: pool.totalCount, idle: pool.idleCount });
process.exit(0);
text
request 1: got a client, never released it
request 2: got a client, never released it
request 3: timeout exceeded when trying to connect
{ total: 2, idle: 0 }
Node 24.18.0. The third request waited 500 ms and gave up.
The script ends with process.exit(0) on purpose. pool.end() waits for every checked-out client to come back, so with two leaked clients it would never return.
In a real service a leak shows up as requests that suddenly take for ever after a few failures. The next script leaks both clients of a pool with max: 2, starts the orders app on that pool, and sends one request, with a 3-second limit on the client side. It runs twice: first with no connection timeout, then with WAIT_MS=1000.
No connection timeout. The request never got an answer.
text
unhandled: timeout exceeded when trying to connect
status 500 after 1063 ms
`WAIT_MS=1000`. The first line is the server's log line, the second is the client's result.
With no limit the request hangs: there is no error and no log line, and only the client's own timer ends it. With a limit, the wait ends with an error that the central handler logs and turns into a 500, so the problem is visible. This is why the app pool sets connectionTimeoutMillis. The finally block is the cure for the leak itself: it runs whether the transaction committed or threw. One more point: if the connection itself has died, the ROLLBACK in the catch can fail too and hide the first error. Production code often wraps that call so the original error is the one that propagates.
Why can't a transaction run through pool.query()?
Each pool.query() call may use a different connection, and a transaction belongs to one connection. Check out a client with pool.connect() and run every statement on it.
Where does client.release() go, and why?
In a finally block, so the client returns to the pool whether the transaction committed or failed. A leaked client permanently reduces the pool.
After a few failed transfers every request to the API hangs and nothing is logged. What do you suspect, and which pool setting turns the hang into a visible error?
A client that was checked out and never released, because some path skipped release(). Setting connectionTimeoutMillis makes the wait for a connection fail with an error, which the handler logs and answers with a 500. The fix for the cause is release() in a finally block.
Part 6 · Database errors at the boundary
Errors from the database are part of the API
The database enforces rules your code also checks. A unique constraint refuses a second order with the same reference. A check constraint refuses a quantity of 0. When two requests race, even code that checks first can lose, so the constraint is the real guard and your handler has to translate its error into the right response.
The pg driver throws an error object with extra fields. The code is a five-character SQLSTATE, a standard error code, and constraint names the rule that was broken. The PostgreSQL documentation says applications should test the code and not the message, because the codes are less likely to change between releases and do not change with the language of the error messages. This script inserts a reference that already exists.
Node 24.18.0. FEST-1001 was inserted by the setup script.
The code 23505 is unique_violation in the PostgreSQL error code appendix. The same table lists 23514 as check_violation, 23502 as not_null_violation and 23503 as foreign_key_violation. The detail text can hold data from the row, so a response should not echo it.
A central error handler
Every route can now throw: our HttpError for input problems and database errors for the rest. One handler turns them all into responses. It checks for our own status first, then looks the SQLSTATE up in a table, and answers 500 with a fixed message for anything it does not know, after logging the real one on the server.
js
const BY_CODE = {
'23505': [409, 'that reference already exists'],
'23514': [400, 'a value breaks a rule of the table'],
'23502': [400, 'a required value is missing'],
'22021': [400, 'text holds a character the database cannot store'],
};
exportfunction errorHandler(err, req, res, next) {
if (res.headersSent) return next(err);
if (err.status) {
return res.status(err.status).json({ error: err.message });
}
const mapped = BY_CODE[err.code];
if (mapped) {
const [status, error] = mapped;
const body = { error, constraint: err.constraint };
return res.status(status).json(body);
}
console.error('unhandled:', err.message);
res.status(500).json({ error: 'internal error' });
}
A client can learn from a 409 and a constraint name which rule it hit. The 500 case sends a generic message because a raw message can reveal table names or SQL. The server log has the real one.
First the app runs with the handler from the earlier lesson, which only knows HttpError, then with the new one. Both get the same two requests: an insert, then the same insert again.
text
== first insert
HTTP/1.1201 Created
Location: /orders/20
{
"id": "20",
"ref": "FEST-3001",
"customer": "Divya",
"item": "tea",
"qty": 2,
"status": "placed"
}
== same ref again
HTTP/1.1500 Internal Server Error
{
"error": "internal error"
}
The old handler. The first insert works and the second hits the unique constraint.
text
== first insert
HTTP/1.1201 Created
Location: /orders/22
{
"id": "22",
"ref": "FEST-3001",
"customer": "Divya",
"item": "tea",
"qty": 2,
"status": "placed"
}
== same ref again
HTTP/1.1409 Conflict
{
"error": "that reference already exists",
"constraint": "orders_ref_key"
}
The new handler. Same two requests.
The old handler returned 500, which tells the client the server broke, so a client may retry for ever. The new one returns 409 Conflict, which says the request clashes with existing data and retrying it will not help.
Two layers of checks
The table also has check (qty > 0), so a quantity of 0 fails even if a route forgets to validate it. Inserting 0 directly shows the database's side of it.
Keep both layers. The hand checks in the route give a clear message for the common mistakes. The constraints stop everything else, including a bug in the route, and the handler maps the code 23514 to a 400.
Hand validation and limits
Validation in validate.mjs is small on purpose: types, ranges and lengths for four fields. A schema library does it with less code, and the API design chapter shows one. The point here is to stop bad data before the database, with a message that a person can act on.
The body size is the other edge. express.json() stops reading a body that is too large, and the error it raises carries a 413 status, which the handler passes through. A body of 150,025 bytes is sent below.
text
body bytes: 150025413 {
"error": "request entity too large"
}
Node 24.18.0. The body is larger than the parser's default limit of 100 KB.
The default limit of express.json() is 100 KB, so this request never reached the route. You can raise it with the limit option, but pick a number that matches the largest real request, and no more.
Inputs that slip past a check
Probing the API with odd input found two gaps in a first version. An offset of 1e20 is a whole number in JavaScript, but too large for the database's bigint, and a NUL character (\u0000) in a text value is something PostgreSQL text cannot hold. Both reached the database and came back as a plain 500, with out of range for type bigint and invalid byte sequence for encoding "UTF8": 0x00 in the server log. The first is fixed in parsePaging, which now uses Number.isSafeInteger and so refuses numbers beyond 2^53 - 1. The second is fixed in the handler's table, where SQLSTATE 22021 (character_not_in_repertoire in the error code appendix) maps to 400.
text
offset=1e20
{
"error": "offset must be 0 to 2^53 - 1"
} [400]
NUL in ref
{
"error": "text holds a character the database cannot store"
} [400]
Node 24.18.0 against the lab database, with the current handler and `parsePaging`.
The lesson: a client can send values that pass your type checks and still break a rule below them. The central handler is the net that catches the rest, and an error that returns a clean 4xx or a logged 500 is better than a crash.
Which field of a pg error should you test to find a duplicate key, and what is its value?
err.code, which is '23505' (unique_violation). Test the code, not the message text.
Why does the 500 branch of the handler send a fixed message?
The raw message can reveal table names, constraint names or SQL. The handler logs the real error on the server and tells the client only that something failed.
Which status fits a duplicate ref: 400, 409 or 500?
409 Conflict. The request is well formed but clashes with existing data. A 500 would say the server failed and invite pointless retries.
Part 7 · Finishing the project
Paging a list
GET /orders returns every order, which is fine for three rows and bad for three lakh. A list endpoint needs a page. The simplest scheme is limit and offset: limit is the page size and offset skips that many rows first.
The PostgreSQL documentation gives one rule: when you use LIMIT, add an ORDER BY that gives a unique order, or you get an unpredictable subset of rows. The route below orders by id, caps limit at 50 through parsePaging, and returns the paging values with the rows.
Offset paging has a cost. The documentation warns that rows skipped by OFFSET still have to be computed inside the server, so a large offset might be inefficient. It also skips or repeats rows when new rows arrive between two page requests. The API design chapter covers the alternative, keyset paging.
A test that calls the API
A test that calls the running API with fetch catches mistakes that unit tests miss: a wrong status, a missing header, a route that never connects. The test below uses the built-in runner, node:test. It starts the app on port 0, which asks the operating system for a free port, so tests never fight over one. The before hook starts the server and the after hook closes it and the pool.
start() returns the server and a close() function. server.close() stops accepting new connections and calls back when the open ones have ended. Since Node 19 it also closes keep-alive sockets that are idle at that moment, so the test client's idle socket does not hold the shutdown. The http documentation says so, and the test passed on Node 24.18 with no extra call. A socket that is busy at the moment of close() is a different case, which the scaling chapter measures. Only after the server is closed does pool.end() run. This order is also what graceful shutdown looks like in a real service, and the scaling chapter returns to it.
js
test('create, read back, delete', async () => {
const res = await post(fresh());
assert.equal(res.status, 201);
const created = await res.json();
assert.equal(res.headers.get('location'), `/orders/${created.id}`);
const read = await fetch(`${base}/orders/${created.id}`);
assert.equal((await read.json()).ref, created.ref);
const url = `${base}/orders/${created.id}`;
const del = await fetch(url, { method: 'DELETE' });
assert.equal(del.status, 204);
});
test('a repeated ref is a 409', async () => {
const order = fresh();
const first = await post(order);
assert.equal(first.status, 201);
assert.equal((await post(order)).status, 409);
const { id } = await first.json();
await fetch(`${base}/orders/${id}`, { method: 'DELETE' });
});
test('limit caps the page and bad input is a 400', async () => {
const page = await (await fetch(`${base}/orders?limit=2`)).json();
assert.equal(page.orders.length, 2);
const bad = await fetch(`${base}/orders?limit=500`);
assert.equal(bad.status, 400);
});
text
✔ create, read back, delete (85.76ms)
✔ a repeated ref is a 409 (26.8322ms)
✔ limit caps the page and bad input is a 400 (17.5778ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 456.3179
`node --test` on Node 24.18.0 against the lab database. The two tests that write use fresh references.
The two tests that write make their own data with a random reference and delete it again, so they do not depend on an empty table and do not collide with each other. Tests that write to a shared database need one of these habits. The testing chapter builds on this with a database per test file.
Configuration from the environment
Port numbers and passwords in source files are a problem as soon as the code runs anywhere but your machine. The usual rule is to read them from environment variables, and the pool accepts a connectionString in the form postgres://user:password@host:port/database. Here the script reads DATABASE_URL and an optional PG_POOL_MAX. Node's --env-file flag from the first chapters can load a file of such lines. The password here is empty because the lab server has none.
Run as DATABASE_URL=postgres://postgres@127.0.0.1:55650/postgres PG_POOL_MAX=6 node l7-config.mjs.
The pool picked up the database from the URL and the size from the variable. Keep the real URL out of the repository, and fail at start-up if the variable is missing, which the scaling chapter shows.
What you built
The API has five routes over one resource, input checks, parameterised queries, a transaction helper, one error handler that understands database codes, and a test. The pieces and where they live:
File
Job
pool.mjs
One pool for the process, max: 4, a 2-second connection timeout
validate.mjs
Checks ids, bodies and paging values
orders-router.mjs
The five order routes
errors.mjs
HttpError and the central handler
main.mjs
Starts the app and closes it in order
Why does the list query need ORDER BY with LIMIT?
Without a unique order, Postgres may return an unpredictable subset of rows, so two pages can overlap or miss rows. Ordering by id fixes the order.
Why does the test start the server on port 0?
Port 0 makes the operating system pick a free port, so tests never clash with another process or each other. The test reads the port from server.address().
In what order should shutdown close things, and why?
Stop the server first, so no new requests arrive, then end the pool. If the pool closed first, a request still running would find its connections gone.