Skip to content

Store your users in Postgres

Working knowledgeBuild alongNode + PostgresYou need: Build a REST API
What you’ll build: The same users API, now backed by a Postgres table. Schema changes live in numbered migration files, every query goes through one connection pool, and users survive a restart. Eight steps, with a command after each to prove it works.SQL users table001 migrations/ applied in orderPOOL one pg.Pool for every queryGET /users from the database503 /health when Postgres is down
Step 1 of 8

Start from your users API

Start from the finished project from Build a REST API from nothing: a users-api folder with Express installed, server.js, and the user routes in routes/users.js.

If you don't have it any more, run the commands below and copy in the two files.

WHY

Right now routes/users.js keeps users in an array, so every restart empties it. The rest of this build swaps that array for a Postgres table without changing what the API looks like from outside.

This step runs:
terminal
$ mkdir users-api && cd users-api
$ npm init -y
$ npm install express
server.jsnew+14−0
Added: const express = require('express');
Added: const usersRouter = require('./routes/users');
Added: const app = express();
Added: app.use(express.json());
Added:
Added: app.get('/health', (req, res) => {
Added: res.json({ ok: true });
Added: });
Added:
Added: app.use('/users', usersRouter);
Added:
Added: app.listen(3000, () => {
Added: console.log('Listening on http://localhost:3000');
Added: });
routes/users.jsnew+24−0
Added: const express = require('express');
Added: const router = express.Router();
Added: const users = [];
Added:
Added: router.get('/', (req, res) => {
Added: res.json(users);
Added: });
Added:
Added: router.post('/', (req, res) => {
Added: if (!req.body?.name) {
Added: return res.status(400).json({ error: 'name is required' });
Added: }
Added: const user = { id: users.length + 1, name: req.body.name };
Added: users.push(user);
Added: res.status(201).json(user);
Added: });
Added:
Added: router.get('/:id', (req, res) => {
Added: const user = users.find((u) => u.id === Number(req.params.id));
Added: if (!user) return res.status(404).json({ error: 'Not found' });
Added: res.json(user);
Added: });
Added:
Added: module.exports = router;

Where to go next

Was this tutorial useful?Your vote tells us what to improve next.
Did a step not work, or something unclear?