Databases for Node apps

Topic 1 of 4 in Databases7 min readIntermediateFree course

Overview

Almost every API needs to store data that survives restarts: users, orders, courses, progress. In memory isn’t enough — it vanishes when the process stops, and isn’t shared between copies of your app. You need a database.

This chapter uses PostgreSQL (often just “Postgres”), the most popular open-source relational database and a superb default for Node APIs. The ideas — pools, parameters, transactions, migrations, caching — apply to any database.

Where data lives

A stateless Node.js API connected to three stores: PostgreSQL as the source of truth for users, orders and courses; Redis for fast, temporary data such as caches, sessions and queues; and object storage such as S3, R2 or GCS for uploads and exports. The app keeps nothing important in memory or on local disk, so any copy can serve any request.

A typical production API uses several stores, each for what it’s best at:

  • A relational database — the source of truth. Anything you’d be upset to lose.
  • Redis — a very fast in-memory store for caches, sessions, rate-limit counters and job queues. Data here should be re-creatable.
  • Object storage — files: uploads, images, exports, backups.

The Node app itself keeps nothing important in memory or on its local disk. That’s what lets you run several copies behind a load balancer and restart any of them at any time.

SQL or NoSQL?

Relational (SQL) databases — PostgreSQL, MySQL, SQLite, SQL Server — store data in tables with a fixed schema, linked by keys. They excel at:

  • data with relationships (users have enrolments in courses which have lessons),
  • guaranteed consistency (transactions, constraints, foreign keys),
  • flexible queries you didn’t plan for (reports, analytics),
  • decades of tooling and expertise.

Non-relational (NoSQL) databases cover several different designs:

Type Examples Good for
Document MongoDB, Firestore flexible, nested JSON-like records
Key–value Redis, DynamoDB very fast lookups by key, caches
Wide-column Cassandra huge write volumes across many servers
Search Elasticsearch, OpenSearch full-text search and relevance ranking

For most business applications, start with PostgreSQL. It also stores and queries JSON (jsonb columns) when you need flexibility, has full-text search built in, and scales much further than most apps ever need. Reach for other stores when you have a specific need they meet better.

Three ways to talk to a database

Approach Example tools You write Trade-off
Driver pg, mysql2, better-sqlite3 raw SQL full control and speed; more typing
Query builder Kysely, Knex JavaScript that builds SQL composable and safer; still close to SQL
ORM Prisma, Drizzle, Sequelize, TypeORM models and methods (user.findMany()) fastest to start; less control, a layer to learn
JavaScript
// Driver
const { rows } = await pool.query('SELECT * FROM courses WHERE level = $1', ['Beginner']);

// Query builder (Kysely)
const rows = await db.selectFrom('courses').selectAll().where('level', '=', 'Beginner').execute();

// ORM (Prisma-style)
const rows = await prisma.course.findMany({ where: { level: 'Beginner' } });

This course uses the pg driver with plain SQL. That isn’t a judgement against ORMs — it’s because SQL is the one skill that transfers to every tool and every language, and understanding what your queries actually do makes you far better at using any ORM later. With a layered project structure, only the repository files would change if you adopted one.

Whatever you choose

Four practices apply to every database and every tool:

  1. Use a connection pool — opening a connection per request is slow and exhausts the database.
  2. Use parameterised queries — never build SQL by gluing strings together (SQL injection).
  3. Use transactions when several changes must succeed or fail together.
  4. Use migrations — versioned scripts that change the schema the same way on every machine.

The next two topics cover all four.

Running Postgres locally

The easiest way is Docker — every developer gets an identical database with one command, without installing Postgres on their machine:

Terminal
docker run --name academy-db -d -p 5432:5432 \
  -e POSTGRES_USER=app -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=academy \
  postgres:17

Or, better, describe it in a docker-compose.yml committed to the project (you’ll write one in Docker for Node). Then put the connection string in .env:

Text
DATABASE_URL=postgres://app:secret@localhost:5432/academy

A connection URL has the form postgres://user:password@host:port/database. In production it comes from your hosting provider and is kept secret.

To explore your data, use psql (the command-line client), or a GUI such as TablePlus, DBeaver, pgAdmin or the database view in your editor.

Managed databases — Neon, Supabase, Amazon RDS, Google Cloud SQL and others — run Postgres for you in production, with backups and updates included. You use them with exactly the same DATABASE_URL and driver.

Exercise

Run PostgreSQL locally

Start PostgreSQL in Docker, connect with psql, create a courses table, insert two rows and select them. Put the connection string in your .env as DATABASE_URL.

Terminal
# start Postgres 17 in Docker, then connect with psql

Summary

  • Your database is the source of truth; the Node app should be stateless.
  • Relational databases (PostgreSQL, MySQL) suit most business data; document and key–value stores suit specific needs.
  • Talk to a database through a driver, a query builder or an ORM — each trades control for convenience.
  • Use a connection pool, parameterised queries and migrations whatever tool you choose.
  • Run your database in Docker locally so every developer has the same setup.