Skip to content

15 min read

Connect Node.js to PostgreSQL with TypeScript

In one sentence: Your server talks to PostgreSQL through a driver, pg, which keeps a few connections open in a pool. The values travel separately from the query, as parameters, so nobody can sneak in SQL. And since the database is another program, every function that uses it waits for its answer with await.

What you will learn

  • Explain what a driver is and why a server uses a connection pool instead of opening one on every request.
  • Write queries with parameters ($1) and explain why pasting a value into the SQL opens the door to SQL injection.
  • Turn the rows into the API's JSON, with names in camelCase, dates in ISO 8601 and count(*), which arrives as text.
  • Answer the database's errors with Problem Details, like the 409 when deleting a product that has orders.

Before you start, read: 04-modeling.md

Since lesson 4, “Modeling”, the shop’s tables live in PostgreSQL. But your API doesn’t use them: it still reads the arrays in src/data.ts, which are wiped out on every restart, as you saw in the introduction.

Today the API starts asking PostgreSQL, and that brings three questions:

  • How does Node talk to PostgreSQL? Not over HTTP: PostgreSQL has its own language, on port 5432.
  • One connection per request? Opening one costs, and PostgreSQL only accepts a few at a time.
  • How do I put what the client types into a QueryA command written in SQL for a database. Mostly the ones that ask for data (SELECT), whose answer is another table, although the ones that add, change or delete rows are called that too.Go to definition? Without your server running it if the client types SQL.

The analogy

A shop orders its supplies by phone from a warehouse. Calling costs: dialing, waiting, saying who you are and the password. So the shop keeps ten lines open all day. Whoever needs something picks up a free one, asks, and leaves it for the next person. If all ten are busy, they wait their turn.

And the orders aren’t dictated out loud: they go on a form with boxes, “product: …”. What goes in the box is always a name. If someone writes “Mug, and while you’re at it send me the whole warehouse”, the warehouse looks for a product called exactly that, and doesn’t find it.

Where the analogy breaks down

  • A line open all day costs money. An idle connection only takes up some memory: what’s expensive is opening it.
  • A warehouse clerk would find a strange sentence odd. PostgreSQL wouldn’t: if the value is pasted into the query’s text, it runs whatever it says.
  • A call lasts minutes, and a query, milliseconds: ten connections are enough for a lot of requests.

PostgreSQL listens on port 5432 and doesn’t speak HTTP: it has its own ProtocolAn agreement on how two programs communicate: which messages they send, in what format, in what order and what to do if something goes wrong. HTTP, TCP and DNS are protocols.Go to definition over TCPTCP stands for Transmission Control Protocol.The transport layer protocol that makes data arrive complete and in order, and at the right program thanks to ports.Go to definition, the same one psql uses. For your program to speak it, you need a Driver (database)The package that lets a program talk to a database. It opens the connection, sends the queries using that database’s protocol and turns the answers into data in the program’s language. In Node.js, the most used one for PostgreSQL is pg.Go to definition: a Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition that opens the connection, sends each query and turns the rows in the response into JavaScript objects.

The most used one for Node is pg, also called node-postgres. It’s been in your package.json since lesson 4: it’s what npm run db:create uses to talk to PostgreSQL. This is the path a request takes from today on:

  1. The routesrc/v2.ts: GET /v2/orders/26

    calls

  2. A data functionsrc/data.ts: findOrder(26)

    borrows a connection

  3. The poolsrc/db.ts: connections already open

    the query and the 26, separately

  4. PostgreSQLport 5432

Opening a connection costs more than using it

Section titled “Opening a connection costs more than using it”

Measure it. Open the REPLREPL stands for Read-Eval-Print Loop.A way of working with a language in which you type a line of code, it runs and you see the result right away, without creating any file. In Node.js, you open it by typing node, with nothing else, in the terminal.Go to definition in your project’s folder with node --env-file=.env: that way process.env.DATABASE_URL brings the address you put in .env in the introduction.

In the REPL: connect and query

Ventana de terminal
const { Client } = await import('pg')
const client = new Client({ connectionString: process.env.DATABASE_URL })
console.time('connect'); await client.connect(); console.timeEnd('connect')
console.time('query'); await client.query('SELECT 1'); console.timeEnd('query')
await client.end()

What you will see:

undefined
undefined
connect: 19.467ms
undefined
query: 1.346ms
undefined
undefined

A Client is a single connection, and console.time and console.timeEnd measure what happens between the two. Connecting took more than ten times as long as the query. Your times will be different; this lesson’s outputs are from Node 26 and PostgreSQL 18.6.

A lot happens when you connect: the TCP HandshakeThe exchange of messages two endpoints use to open a connection before sending data. In TCP there are three (SYN, SYN-ACK and ACK), and they cost one round trip.Go to definition from Phase 0, the password check and, on the server, a new PostgreSQL ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition just for that connection. With the database on another machine, each round trip weighs more.

And there’s no room for infinitely many:

How many connections does it accept?

Ventana de terminal
psql -d shop -c 'SHOW max_connections;'

What you will see:

max_connections
-----------------
100
(1 row)

A hundred, PostgreSQL’s default, and three are reserved for the superuser. If your API opened one connection per request, with 97 requests at once the next one would get an error: remaining connection slots are reserved for roles with the SUPERUSER attribute.

A pool: open connections that are lent out

Section titled “A pool: open connections that are lent out”

The solution is a Connection poolA few connections to the database that a server keeps open and reuses. Each query takes a free one and gives it back when it’s done. Opening a connection costs much more than using it, and the database only accepts a limited number at a time.Go to definition, a few that are reused, in a new file, src/db.ts:

src/db.ts
// The database's address, from .env: postgres://user:password@server:port/database
const url = process.env.DATABASE_URL;
if (url === undefined) {
console.error('Configuration: DATABASE_URL: DATABASE_URL is missing (see .env.example)');
process.exit(1);
}
// A pool: a few open connections that the requests borrow in turn. Opening a connection costs
// (TCP, the password, setting up the session); reusing an open one, almost nothing. At most 10 at
// a time: if more queries arrive, they wait their turn.
export const pool = new Pool({ connectionString: url, max: 10 });
// If PostgreSQL closes a connection that was waiting in the pool (because it restarts, for
// example), the pool reports it with an 'error'. With nobody listening, Node would stop the server.
pool.on('error', (error) => {
console.error('PostgreSQL closed a connection in the pool:', error.message);
});
  • process.env.DATABASE_URL is the address in .env. Without it, the server doesn’t start and says why, like config.ts since lesson 8 of Phase 3.
  • new Pool({ connectionString: url, max: 10 }) creates the pool, with ten connections at most. It opens them when they’re needed, and closes the ones that have gone ten seconds without being used.
  • pool.on('error', …): if PostgreSQL closes a connection that was waiting in the pool (when it restarts, for example), the pool reports it with an error. With nobody listening, Node would stop the server.
  • export const pool: a single pool for the whole program, the same one in every file that imports it.

Are ten enough? With queries of a couple of milliseconds, each connection handles hundreds per second. If none is free, the query waits its turn in the pool.

A query with $1: the value travels separately

Section titled “A query with $1: the value travels separately”

A data function, in src/data.ts:

src/data.ts
// $1 is a parameter: the query and the value travel separately, and PostgreSQL never reads the
// value as SQL. If there's no row, rows[0] is undefined.
export async function findProduct(id: number): Promise<Product | undefined> {
const { rows } = await pool.query<Product>(`SELECT ${PRODUCT} FROM products WHERE id = $1`, [id]);
return rows[0];
}
  • pool.query(query, [id]): the pool lends a connection, sends the query and takes the connection back when it’s done.
  • $1 is a parameter: a slot for a value. The first element of the array, id, goes in $1; if there were a $2, the second one would go there. The query and the values travel separately, and PostgreSQL never reads a value as SQL.
  • <Product> tells TypeScript what shape the rows have. You’re the one claiming it: pg doesn’t check it.
  • rows is an array with the rows. If that id doesn’t exist, it’s empty and rows[0] is undefined: the route answers 404.
  • ${PRODUCT} is pasted in, but it’s fixed text from the program, the list of columns. What the client sends, never.

Pasting the value into the text: SQL injection

Section titled “Pasting the value into the text: SQL injection”

Why not write the value inside, with ${id}? Look at examples/injection.ts, a search by name written both ways:

examples/injection.ts
// WRONG: the value the client sends, pasted into the query's text.
async function searchByPasting(name: string) {
const query = `SELECT name FROM products WHERE name = '${name}' ORDER BY id`;
console.log(` The query: ${query}`);
const { rows } = await pool.query(query);
return rows.map((row) => row.name);
}
examples/injection.ts
// RIGHT: the query carries $1, and the value travels separately. PostgreSQL gets the two things
// apart and never reads the value as SQL: it looks for a product with exactly that name.
async function searchWithParameter(name: string) {
const query = 'SELECT name FROM products WHERE name = $1 ORDER BY id';
const { rows } = await pool.query(query, [name]);
return rows.map((row) => row.name);
}

With “Mug”, both find the Mug. But imagine someone types this into the search box: x' OR '1'='1. The first function pastes it between the quotes, and this is the query that reaches PostgreSQL:

SELECT name FROM products WHERE name = 'x' OR '1'='1' ORDER BY id

The value’s quote has closed the query’s, and what comes after it is already SQL: OR '1'='1', which is true for every row. It returns all four products.

That’s SQL injectionSQL stands for Structured Query Language.An attack that sends a value crafted so that, pasted inside the text of a query, it changes what the query does, such as returning every row or deleting a table. It’s prevented by sending the values separately, as parameters, and never pasting them into the SQL.Go to definition: a value written to change the query. With other values, someone can read other tables, or delete them; Phase 6 covers it in depth. The rule, from today on: what the client sends always goes in a parameter. With $1, PostgreSQL looks for a product called exactly x' OR '1'='1, and there’s none.

The validation from Phase 3 isn’t enough: x' OR '1'='1 is a valid text. Validate and, on top of that, use parameters.

From rows to JSON: names, dates and count(*)

Section titled “From rows to JSON: names, dates and count(*)”

Look at how the rows arrive, in the REPL, this time with a pool:

In the REPL: the rows as they arrive

Ventana de terminal
const { Pool } = await import('pg')
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
(await pool.query('SELECT * FROM orders WHERE id = 1')).rows
(await pool.query('SELECT price_cents AS priceCents FROM products WHERE id = 2')).rows
(await pool.query('SELECT price_cents AS "priceCents" FROM products WHERE id = 2')).rows
(await pool.query('SELECT count(*) FROM orders')).rows
(await pool.query('SELECT count(*)::int AS orders FROM orders')).rows

What you will see:

undefined
undefined
[
{
id: 1,
product_id: 2,
quantity: 2,
status: 'shipped',
created_at: 2026-10-01T09:00:00.000Z
}
]
[ { pricecents: 850 } ]
[ { priceCents: 850 } ]
[ { count: '25' } ]
[ { orders: 25 } ]

Notice four things:

  • The row brings the columns’ names, product_id and created_at, and your API promises productId and createdAt.
  • created_at arrives without quotes: it’s a JavaScript Date. That’s how pg converts every timestamptz.
  • AS priceCents arrives in lowercase: PostgreSQL lowercases names without double quotes. With them, it keeps the capital letter.
  • count(*) arrives as text, '25'. With ::int, as a number.

Why text? count(*) returns a bigint, a 64-bit integer that can go past 2⁵³, the limit of exact integers in JavaScript (lesson 6 of Phase 4). So as not to change it without warning, pg hands it over as text; if you know it fits, ::int converts it in the query. Without converting it, '25' + 1 gives '251'.

The names are fixed in the query itself, with AS, at the top of src/data.ts:

src/data.ts
// The columns, with the name they have in the API: price_cents AS "priceCents". The quotes make
// PostgreSQL keep the capital letter (without them, it would make it lowercase). That way, each
// row is already a product just as it appears in the JSON. It's our own fixed text: nothing the
// client sends is ever pasted into a query.
const PRODUCT = 'id, name, price_cents AS "priceCents"';
const ORDER = 'id, product_id AS "productId", quantity, status, created_at AS "createdAt"';
// pg turns each timestamptz into a JavaScript Date. The API gives it as text: toISOString()
// writes it in ISO 8601 and always in UTC, whatever the server's time zone.
type OrderRow = Omit<Order, 'createdAt'> & { createdAt: Date };
const toOrder = (row: OrderRow): Order => ({ ...row, createdAt: row.createdAt.toISOString() });
  • PRODUCT and ORDER are the lists of columns, with the API’s names: each row already comes out as it is in the JSON.
  • OrderRow is an Order with createdAt as a Date, which is how it arrives.
  • toOrder turns that date into text with toISOString(): ISO 8601 and in UTC, as in Phase 4.

Before, findProduct(id) looked in an array in memory and returned the product instantly. Now it asks another program over the network, and you have to wait: the function is async and returns a PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition, Promise<Product | undefined>.

That spreads upward. In src/v2.ts, every route that uses the data becomes async (c) => … and writes await findProduct(…); the same in src/v1.ts and in the idempotency middleware. It’s the async and awaitTwo JavaScript words for waiting for something that takes time, like reading a file or receiving a response, without stopping everything else. await waits for a promise to arrive, and async marks the function that uses it.Go to definition from lesson 2 of Phase 3. And while one request waits for PostgreSQL, Node serves the others: waiting doesn’t block.

In the same REPL, try to delete the T-shirt, which has orders:

In the REPL: a delete PostgreSQL rejects

Ventana de terminal
await pool.query('DELETE FROM products WHERE id = 1').catch((error) => [error.code, error.detail])
await pool.end()

What you will see:

[ '23503', 'Key (id)=(1) is still referenced from table "orders".' ]
undefined

PostgreSQL won’t let you delete it: the Foreign keyA column that stores the primary key of a row in another table, such as the product number of each order. The database won’t let you save a value that doesn’t exist in the other table and, unless told otherwise, won’t let you delete a row that others point to either.Go to definition from lesson 4 prevents it. pg turns the rejection into an error with a five-character code, the SQLSTATE, the same in any PostgreSQL, and detail describes the case. pool.end() closes the pool so the REPL can exit.

Two codes matter here:

Code Name When
23505 unique_violation A repeated value where it has to be unique: two categories called “Clothing”
23503 foreign_key_violation A foreign key that doesn’t add up: deleting a product that has orders

If you did nothing, that error would reach the onError in src/app.ts and become a 500. But the server hasn’t failed: the request clashes with data that already exists. That’s a 409 Conflict (lesson 3 of Phase 2), in the shape of Problem DetailsThe standard shape of the body of an error response in an API, written down in RFC 9457: a JSON with type (what kind of problem it is), title (its summary), status (the status code), detail (what happened this time) and instance (which of the times). It’s sent with the content type application/problem+json.Go to definition. src/problems.ts decides it:

src/problems.ts
// When PostgreSQL rejects a change, it says which rule was broken with a five-character code
// (SQLSTATE). Two of them aren't a server failure, but a clash with the data already there: 409
// Conflict. The rest are still a 500.
const CONFLICTS: Record<string, string> = {
// unique_violation: that value is already there, and it can't be repeated.
'23505': 'The same data already exists, and it cannot be repeated',
// foreign_key_violation: other data points to this with its foreign key.
'23503': 'Other data depends on this: a product with orders, for example, cannot be deleted',
};
// Returns the 409, or undefined if the error isn't one of those.
export function dbConflict(c: Context, error: unknown) {
const detail = error instanceof DatabaseError ? CONFLICTS[error.code ?? ''] : undefined;
return detail === undefined ? undefined : httpProblem(c, 409, detail);
}
  • error instanceof DatabaseError: only PostgreSQL’s errors. A bug in your code is still a 500.
  • CONFLICTS[error.code ?? ''] gives the text for the client, or undefined if the code isn’t one of those two.
  • Neither error.message nor error.detail is sent: they name tables and internal rules, and that never goes in an error.

onError calls dbConflict before the 500, and src/contract.ts adds the 409 to DELETE /v2/products/{id} in the documentation.

The idempotency keys and the payment notifications, in tables

Section titled “The idempotency keys and the payment notifications, in tables”

In Phase 4, two more things lived in memory: the responses for each Idempotency keyA unique value the client sends in the Idempotency-Key header along with an operation, such as creating an order. If it repeats the request with the same key, the server returns the first response instead of doing it again.Go to definition, in a Map, and the ids of the WebhookAn address on your server that another service sends a request to when something happens, such as a completed payment. Instead of you asking every so often whether something has changed, they let you know.Go to definition already processed, in a Set. After a restart, a retry would create a repeated order. They move to two new tables in db/schema.sql:

db/schema.sql
-- The responses stored for each Idempotency-Key (Phase 4): in a table, a server restart no longer
-- forgets them.
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
-- The request's body: if the same key arrives with other data, it's a client error.
request_body text NOT NULL,
-- The response that was given: the status code, the body and the Location header, if it had one.
status integer NOT NULL,
body text NOT NULL,
location text,
-- When it was stored: with this, the ones older than a day can be deleted.
created_at timestamptz NOT NULL DEFAULT now()
);
db/schema.sql
-- The ids of the payment gateway's notifications already processed. The primary key stops the
-- same id from getting in twice: that's how you know a notification is repeated.
CREATE TABLE processed_events (
id text PRIMARY KEY,
-- DEFAULT now(): unless told otherwise, the current time.
processed_at timestamptz NOT NULL DEFAULT now()
);

The key itself, or the event’s id, is the Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition: it can’t be repeated. Recording an event is a single query:

src/data.ts
// Writes down the id of a payment notification. If it was already there, the primary key stops it
// and ON CONFLICT DO NOTHING makes nothing happen: RETURNING returns no row. It's a single query,
// so even if the same notification arrives twice at once, only one writes it down. Returns
// whether it was new.
export async function recordEvent(id: string): Promise<boolean> {
const { rowCount } = await pool.query(
'INSERT INTO processed_events (id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING id',
[id],
);
return rowCount === 1;
}
  • ON CONFLICT DO NOTHING: if the id is already there, the primary key would reject it with a 23505; this way, PostgreSQL does nothing and there’s no error.
  • RETURNING id returns the row added. If none was added, rowCount is 0: the notification was a repeat.

Before, it was two steps, has and add, and if the same notification arrived twice at once, both could see it as new. Now PostgreSQL decides: only one records it.

In src/middleware/idempotency.ts, the Map is replaced by a SELECT and an INSERT. Only the real-time events and the WebSocket echo stay in memory: they’re connections, not data.

The goal: get your API to store everything in PostgreSQL and prove it. An order and its idempotency key that survive a restart, a 409 instead of a 500, and the example’s search, fooled and protected.

You start from your project from lesson 4, “Modeling”:

  1. Create src/db.ts, with the pool.
  2. Change src/data.ts: each array becomes queries, and each function, async. The ones you haven’t seen here, copy them from the step.
  3. Add async and await wherever the data is used: src/v2.ts, src/v1.ts and src/middleware/idempotency.ts.
  4. Change src/problems.ts (dbConflict), src/app.ts (onError) and src/contract.ts (the 409).
  5. Add the two tables to db/schema.sql, and their names to the DROP TABLE in scripts/create-db.ts.

The example and the tests come in this lesson’s folder:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/19-postgres.tar.gz
tar -xzf 19-postgres.tar.gz
cd shop-api
cp ../19-postgres/examples/injection.ts examples/
cp ../19-postgres/test/*.ts test/

If you get stuck, compare your code with 19-postgres.

1. Create the tables again

Ventana de terminal
npm run db:create

What you will see:

> shop-api@1.0.0 db:create
> node --env-file-if-exists=.env scripts/create-db.ts
Tables created: 4 products, 3 categories and 25 orders

The script drops the tables and creates six, with the sample data: your shop database goes back to the start. If you get ECONNREFUSED, PostgreSQL isn’t running: start it as in the introduction.

Then, npm test should end with fail 0. The tests use shop_test; if the first one says Is PostgreSQL running?, check that database.

2. Start the API

Ventana de terminal
npm start

What you will see:

> shop-api@1.0.0 start
> node --env-file-if-exists=.env src/server.ts
{"level":30,"time":1791935318041,"pid":692,"hostname":"laptop","msg":"The shop is listening on http://localhost:3000"}

The pool hasn’t opened any connection yet. Leave this terminal open and open another one in the project’s folder.

3. An order with its idempotency key

Ventana de terminal
curl -s -w '\n' -H 'Idempotency-Key: ana-order-1' --json '{"productId":2,"quantity":1}' localhost:3000/v2/orders
curl -s -w '\n' localhost:3000/v2/orders/26

What you will see:

{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:48:40.838Z"}
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:48:40.838Z"}

Order 26, a mug. PostgreSQL set the id, and the date, now(), is the database’s time. Your date will be different.

Before restarting, look at the pool from the other side:

4. The shop role's connections

Ventana de terminal
psql -d shop -c "SELECT pid, state, query FROM pg_stat_activity WHERE usename = 'shop';"

What you will see:

pid | state | query
-----+--------+-------------------------------------------------------------------------------------------------------------
153 | idle | SELECT id, product_id AS "productId", quantity, status, created_at AS "createdAt" FROM orders WHERE id = $1
160 | active | SELECT pid, state, query FROM pg_stat_activity WHERE usename = 'shop';
(2 rows)

pg_stat_activity is queried like a table, but PostgreSQL fills it: one row for each open connection. The active one is your own psql. The idle one is the pool’s: it waits, free, with its process (pid) and its last query. Notice the $1: the 26 isn’t in the text, because it traveled separately.

Wait ten seconds and run it again: the idle connection is gone, because the pool closes the ones it doesn’t use. The next request will open another one.

Now stop the server with Ctrl + C and start it again with npm start. In the other terminal:

5. After the restart

Ventana de terminal
curl -s -w '\n' localhost:3000/v2/orders/26
curl -s -i -H 'Idempotency-Key: ana-order-1' --json '{"productId":2,"quantity":1}' localhost:3000/v2/orders

What you will see:

{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:48:40.838Z"}
HTTP/1.1 201 Created
content-type: application/json
idempotent-replayed: true
location: /v2/orders/26
vary: Origin
x-request-id: 04afebc6-e7c2-48c4-8a88-f8fc08a25bf0
content-length: 94
Date: Tue, 13 Oct 2026 23:48:46 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:48:40.838Z"}

In the introduction, you got a 404 here. Now order 26 is still there. And the retry with the same key returns the stored response, with idempotent-replayed: true, even though another process stored it.

6. The same, from psql

Ventana de terminal
psql -d shop -c "SELECT * FROM orders WHERE id = 26;" -c "SELECT key, status, location FROM idempotency_keys;"

What you will see:

id | product_id | quantity | status | created_at
----+------------+----------+---------+------------------------------
26 | 2 | 1 | pending | 2026-10-13 23:48:40.83836+00
(1 row)
key | status | location
-------------+--------+---------------
ana-order-1 | 201 | /v2/orders/26
(1 row)

Your API and psql see the same data. Each -c is one command. PostgreSQL stores microseconds; the API cuts them down to milliseconds.

Deleting needs the token from your .env. Put yours instead of this one:

7. Delete the T-shirt, which has orders

Ventana de terminal
TOKEN=6bb3a19879dcf82e36c2e623dff47255dfb115160d44ae38
curl -s -i -w '\n' -X DELETE -H "Authorization: Bearer $TOKEN" localhost:3000/v2/products/1

What you will see:

HTTP/1.1 409 Conflict
content-type: application/problem+json
vary: Origin
x-request-id: a65f7555-6ccd-4975-be8a-23f9129b255e
content-length: 147
Date: Tue, 13 Oct 2026 23:48:46 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"type":"about:blank","title":"Conflict","status":409,"detail":"Other data depends on this: a product with orders, for example, cannot be deleted"}

PostgreSQL’s 23503, turned into a 409 with Problem Details, with no table names. If you get a 500, check that onError calls dbConflict.

8. Pasting the value and with a parameter

Ventana de terminal
node --env-file=.env examples/injection.ts

What you will see:

Searching for: Mug
The query: SELECT name FROM products WHERE name = 'Mug' ORDER BY id
Pasting the text, it finds: [ 'Mug' ]
With a parameter, it finds: [ 'Mug' ]
Searching for: x' OR '1'='1
The query: SELECT name FROM products WHERE name = 'x' OR '1'='1' ORDER BY id
Pasting the text, it finds: [ 'T-shirt', 'Mug', 'Hoodie', 'Cap' ]
With a parameter, it finds: []

With the crafted value, pasting brings out the whole table; with the parameter, nothing.

  • A form that breaks with an apostrophe. If a website has ever given you a strange error when you typed “O’Donnell”, maybe it was pasting your text into the SQL: the apostrophe closes the query’s quote.
  • Little Bobby Tables. The xkcd 327 comic is the best-known joke about SQL injection: a kid named Robert'); DROP TABLE Students;--.
  • Pasting what the client sends into the SQL, with ${…} or with +. It goes in a parameter, $1, even if it’s already validated.
  • Putting a column name or a DESC in a parameter. A parameter is always a value, never a piece of SQL. Whatever changes the query’s shape is chosen from a fixed list, like the SORT list of listProducts, in src/data.ts.
  • Opening a connection, or creating a pool, on every request. A single pool per program, created at startup.
  • Forgetting the await. Without it, product is a promise, never undefined. npm run check usually catches it.
  • Using count(*) without converting it. It arrives as text: ::int, if you know it fits.
  • Sending PostgreSQL’s message to the client. It tells how your tables are built: your own text for the client, and the full error, to the log.
  • Node talks to PostgreSQL through a driver, pg. Opening a connection costs much more than using it, and only a few fit: a pool keeps them open and lends them out.
  • What the client sends always goes in a parameter ($1), separate from the query. Pasting it into the text allows SQL injection.
  • The rows arrive with the columns’ names, which AS "priceCents" changes. A timestamptz arrives as a Date, and count(*), as text.
  • Every function that queries the database is async, and so is whoever calls it.
  • A 23505 or a 23503 is a conflict with the data, not a server failure: 409. The idempotency keys and the processed notifications, in tables, survive a restart.
An API opens a connection to PostgreSQL at the start of every request and closes it when it answers. With little traffic it works fine, but on sale day many requests fail. What’s the most likely cause?

A colleague searches for products by name by pasting what arrives in ?name= into the SQL. They say there’s no danger, because Zod checks that it’s a text under 50 characters. Are they right?

A route returns the total number of orders with SELECT count(*) AS total FROM orders, and in the JSON the total arrives in quotes, as text. Why?

A client tries to delete the Mug, which has orders. What should the API answer?

You change findProduct so it queries PostgreSQL, but in the route you write const product = findProduct(id), without await. Someone asks for a product that doesn’t exist. What happens?

The phone app creates an order with an Idempotency-Key. Right after that, the API restarts with a new version, and the app retries with the same key and the same body. What does it get?

phase-5 · lesson 5/10