Connecting to a Database — Node.js

An array is lost on every server restart, a database stays. Node 24 and later have SQLite built in, a database in one file: const { DatabaseSync } =…

In the notes-api project, you send a POST for the note Workout and get a 201. Then you stop the server with Ctrl+C and start it again. GET /notes answers with only the two old notes. Workout is gone, even though it was clearly saved.

The notes array is like a whiteboard in a classroom: easy to write on, but wiped every time class ends. Here, class ending means the server stops. Real APIs keep their data in a database, a place where data is kept outside the program. A database is like a notebook in a drawer: what's in it is still there when the server stops.

An array is lost when the server stops

An array lives in the memory of the Node process (the Node program while it runs). When the process stops, that memory is thrown away. The next node app.js starts again from the array written in the code.

Step Data in the array Data in the database
server running 2 notes 2 notes
POST Workout 3 notes 3 notes
Ctrl+C, then node app.js 2 notes, Workout is gone 3 notes, Workout is still there

SQLite built into Node 24: node:sqlite

SQLite is a database kept as one ordinary file, with no database server (a separate program that manages the data, like MySQL). Node 24 and later already include SQLite as the module node:sqlite, so there's no npm install. Commands for the database, called statements, are written in SQL, a language for reading and changing data in a database:

const { DatabaseSync } = require("node:sqlite");

const db = new DatabaseSync("notes.db");
db.exec(`
  CREATE TABLE IF NOT EXISTS notes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    content TEXT NOT NULL
  )
`);

On Node 22, node:sqlite still prints ExperimentalWarning: SQLite is an experimental feature and might change at any time. For older Node versions, there's the better-sqlite3 package, which is used the same way (prepare, get, all, run).

Routes that speak SQL

Here are the routes from the CRUD lesson, now reading from and writing to the database:

app.get("/notes", (req, res) => {
  const rows = db.prepare("SELECT * FROM notes").all();
  res.json(rows);
});

app.get("/notes/:id", (req, res) => {
  const row = db.prepare("SELECT * FROM notes WHERE id = ?").get(req.params.id);
  if (!row) return res.status(404).json({ error: "Note not found" });
  res.json(row);
});

app.post("/notes", (req, res) => {
  const { title, content } = req.body;
  const info = db.prepare("INSERT INTO notes (title, content) VALUES (?, ?)").run(title, content);
  const newNote = db.prepare("SELECT * FROM notes WHERE id = ?").get(info.lastInsertRowid);
  res.status(201).json(newNote);
});

app.delete("/notes/:id", (req, res) => {
  const info = db.prepare("DELETE FROM notes WHERE id = ?").run(req.params.id);
  if (info.changes === 0) return res.status(404).json({ error: "Note not found" });
  res.status(204).end();
});

The ? placeholder: the value travels separately

? is a blank in the SQL. Its value is sent to the database separately from the SQL text, so whatever it holds, the value counts as data, not as a command. Compare that with pasting the value directly into the SQL text:

// DANGER: a value from the URL pasted into the SQL text
const info = db.prepare(`DELETE FROM notes WHERE id = ${req.params.id}`).run();
Request SQL that reaches the database Result
DELETE /notes/2 DELETE FROM notes WHERE id = 2 note 2 is deleted
DELETE /notes/0%20OR%201=1 DELETE FROM notes WHERE id = 0 OR 1=1 every note is deleted, 204
the same, with ? DELETE FROM notes WHERE id = ? + the value "0 OR 1=1" nothing matches, 404

In the second row, %20 is how a URL writes a space, so req.params.id holds 0 OR 1=1. This is called SQL injection: user input turns into part of the SQL statement. OR means "or", and 1=1 is always true, so the WHERE matches every row.

Even honest input can break a pasted statement. The title Mom's birthday pasted into an INSERT statement makes VALUES ('Mom's birthday', ...): the apostrophe in Mom's closes the text too early. SQLite refuses it with near "s": syntax error, and Express answers 500. With ?, Mom's birthday is stored as it is.

MySQL and PostgreSQL: drivers and pools

MySQL and PostgreSQL are databases that run as their own server. To use one, Node needs a driver: a package from npm that connects Node to that database. With mysql2:

const mysql = require("mysql2/promise");

const pool = mysql.createPool({ host: "localhost", user: "root", database: "school" });

const [rows] = await pool.execute("SELECT * FROM students WHERE id = ?", [id]);

PostgreSQL with the pg package uses $1, $2 instead of ?.

ORMs and query builders

Many projects don't write SQL by hand. An ORM (Object Relational Mapper) such as Prisma or Sequelize lets you use tables like JavaScript objects: prisma.notes.findMany(). A query builder such as Knex builds queries (SQL statements) through functions: knex("notes").where({ id }). All three still use placeholders in the SQL they create.

There are several databases to choose from:

Database When to pick it
SQLite (node:sqlite) Learning, and an app that runs on one server. This lesson uses SQLite because it comes with Node 24 and later, with no database server.
PostgreSQL or MySQL Production with many users. Services such as Supabase or Neon give you a PostgreSQL that is already running on the internet.
MongoDB with Mongoose Data stored as JSON-like documents whose shape can vary. Many "MERN" (MongoDB, Express, React, Node) tutorials use it.

You can also choose how to reach it: plain SQL with placeholders (this lesson), a query builder such as Knex or Kysely, or an ORM such as Prisma and Drizzle. Sequelize is found more often in older code.

In the exercise: a pretend database made of an array

In the exercise, the products array takes the place of a table. getAllProducts() and the nextId counter are already there. You fill in insertProduct(name, price):

  1. Build { id: nextId++, name, price }.
  2. push that object into products.
  3. return the product, like an INSERT followed by a SELECT of the new row.

When it's right, the starter prints:

All products: 2
INSERT: {"id":3,"name":"Mouse","price":150000}
After insert: 3

⚠️ Mistakes that make a query leak or fail

TL;DR: An array is lost on every server restart, a database stays. Node 24 and later have SQLite built in, a database in one file: const { DatabaseSync } = require("node:sqlite"), new DatabaseSync("notes.db"), then CREATE TABLE IF NOT EXISTS to create the table only once. SQL statements (database commands) run through db.prepare(sql).all() (every row), .get() (one row), or .run() (changes data, returns changes and lastInsertRowid). Values from a request always go through the ? placeholder (a blank in the SQL), never pasted into the SQL text. id = 0 OR 1=1 pasted in deletes every row: that's SQL injection. MySQL: mysql.createPool({...}) then const [rows] = await pool.execute("... WHERE id = ?", [id]). If you'd rather not write SQL by hand, there are ORMs such as Prisma and Sequelize, and query builders such as Knex.

⚡ The array is lost, the database stays

Guess first: your API holds 2 notes. You send a POST for the note Workout, then stop the server and start it again. How many notes does GET /notes answer with?

With the data in an array: 2, Workout is gone. In a database: 3, Workout is still there.

Meaning: An array lives in the memory of the Node process (the Node program while it runs) and is thrown away when the process stops. A database keeps the data outside the program, like a notebook in a drawer whose pages are still there when the server stops.

⚡ SQLite built into Node 24

Write:

const { DatabaseSync } = require("node:sqlite");

const db = new DatabaseSync("notes.db");
const rows = db.prepare("SELECT * FROM notes").all();

Meaning: SQLite is a database kept as one ordinary file, here notes.db. Node 24 and later include it, so there's no npm install. db.prepare(sql) prepares an SQL statement (a database command), for example a SELECT that reads the notes table. Then .all() gets every row, .get() one row or undefined, and .run() is for changing data.

⚡ Values go through ?, never pasted in

Write:

db.prepare("DELETE FROM notes WHERE id = ?").run(req.params.id);

Meaning: This statement deletes the row whose id equals the value for ?, here req.params.id. That value is sent separately from the SQL text, so it always counts as data. Pasted in with ${...}, the input 0 OR 1=1 deletes every note, because 1=1 is always true. That's called SQL injection.

What you will learn