Ch 6 · Talking to Postgres · Next.js
Topic 6 of 7 in Next.js — Build the App You Deploy — 5 lessons.
A Real Database, Not a File
Everything so far kept data in a variable, which disappears the moment the server restarts. A database is what makes an order still be there tomorrow — and "the data survives" is most of what a client is paying for.
Never Build SQL With +
If name is '; DROP TABLE orders; -- then you have just handed a stranger your client's database. This is SQL injection, it is thirty years old, and it still appears in new code every week.
Secrets Live in the Environment
Two rules. Secrets go in an environment file that is listed in .gitignore and never committed. And a missing secret should stop the program immediately with a clear message, rather than failing later with a connection error that says nothing useful.
Closing the Loop
RETURNING hands back the row that was just written, including the id the database generated. That saves a second query, and it means the response you send tells the caller exactly what was stored — not what you hoped was stored.
Check Yourself
There are at least four: string-built SQL, no validation of either field, no status code on creation, and no handling of a database error. Rewrite it using everything from Chapters 5 and 6 before you look at the project below.