What Is the PERN Stack?
By the end of this lesson you will be able to name the four parts of the PERN stack, say where each one runs, and trace one real request from a React button click to a PostgreSQL row and back. You will also meet KharchaBook, the household expense app we build through this course.
What you should know first: basic HTML, CSS and JavaScript, plus a little of one back-end language. You do not need to know PostgreSQL, Express or React yet. Each has its own full course on this site, and we link to the right lesson whenever you need a basic: PostgreSQL Introduction, Node.js Introduction, React Introduction and SQL Introduction. This course spends its time on how the parts fit together.
The four letters
A stack is a set of tools that are used together to build one application. PERN is named after its four main tools:
| Letter | Tool | Its job in the app | Where it runs |
|---|---|---|---|
| P | PostgreSQL | Stores the data in tables and enforces rules on it | Database server |
| E | Express | Receives HTTP requests and sends JSON responses | Inside Node.js on the server |
| R | React | Draws the screens and reacts to clicks and typing | In the user's browser |
| N | Node.js | Runs JavaScript outside the browser | On the server (and on your laptop for tools) |
PostgreSQL (often called "Postgres") is a relational database. It keeps data in tables with rows and columns, and it can refuse bad data, such as a negative amount or a category that does not exist. Express is a small web framework for Node.js. It lets you write "when someone asks for GET /api/expenses, run this function". React is a library for building user interfaces from components. Node.js is the JavaScript runtime that runs Express, and also runs your build tools such as Vite.
The nice part is that you write JavaScript in the browser and on the server. Only the database speaks a different language: SQL.
Who does what: a family ledger
Think of a family in Pune that keeps its accounts in a notebook. Priya writes "Groceries, ₹2,340.50, 2 November" on a slip and hands it to her brother Rohan. Rohan checks the slip: is the amount a real number? Is the date real? Then he copies it into the big ledger kept in the locked almirah. Only Rohan has the key.
- The slip and the pen are React: the screen where Priya types.
- Rohan is Express running on Node.js: he checks every request and decides what to do.
- The locked ledger is PostgreSQL: the permanent record, with its own printed columns that only accept the right kind of entry.
The important rule from this picture: the browser never talks to the database directly. Anyone can open the browser's developer tools and read your front-end code. If the database password were in React code, every visitor would have it. So React talks only to Express, over HTTP, and only Express holds the database password, in an environment variable on the server.
One request, start to finish
Let us follow Priya's grocery entry through the whole stack. The diagram shows the path:
Browser (React) Server (Node.js + Express) PostgreSQL
----------------- ------------------------- ----------
1. Priya clicks "Save"
2. fetch() sends JSON -----> 3. Express reads the JSON body
4. Validates amount, date, category
5. Runs a parameterised INSERT ----> 6. Checks constraints,
saves the row
7. Turns the row into JSON <------ returns it
8. React shows the new <----- 8. Sends 201 Created
row in the listIn step 2, React sends an HTTP request. HTTP is the same protocol your browser uses to load any web page. The request carries JSON (JavaScript Object Notation), a text format for data:
POST /api/expenses HTTP/1.1
Content-Type: application/json
{"amount": "2340.50", "categoryId": 1, "spentOn": "2026-11-02", "note": "DMart monthly ration"}In step 5, Express hands the values to PostgreSQL. The values travel separately from the SQL text, as parameters ($1, $2...). This is what makes SQL injection impossible, and you will use it in every query in this course:
INSERT INTO expenses (amount, category_id, spent_on, note)
VALUES ($1, $2, $3, $4)
RETURNING id, amount, category_id, spent_on, note, created_at;Notice the two naming styles. SQL tables use snake_case (spent_on), the usual style in PostgreSQL. JSON in the API uses camelCase (spentOn), the usual style in JavaScript. Express translates between them in one place, so neither side has to change its habits.
In step 8, Express answers with status 201 Created and the saved expense, including the id and createdAt that only the database could know:
{
"data": {
"id": 1,
"amount": "2340.50",
"categoryId": 1,
"category": "Groceries",
"spentOn": "2026-11-02",
"note": "DMart monthly ration",
"createdAt": "2026-11-16T04:57:11.327Z"
}
}The amount is a string, "2340.50", not a number. That is a deliberate choice for money, and the Build a REST API with Express 5 lesson explains why.
Try the round trip in your browser
The Try-it editor cannot run Express or PostgreSQL, so this example fakes the server with a function that returns a real Response object, exactly like fetch() does. Watch the numbered log lines: they follow the same steps as the diagram.
import { useState } from "react";
import { createRoot } from "react-dom/client";
// A pretend server: in the real app this is Express + PostgreSQL.
let nextId = 2;
async function fakeServer(method, url, body) {
console.log("3. Express received", method, url);
const input = JSON.parse(body);
if (!(Number(input.amount) > 0)) {
console.log("4. Validation failed");
return new Response(JSON.stringify({ error: { code: "VALIDATION_FAILED", message: "Some fields need fixing." } }), { status: 400 });
}
console.log("5-6. INSERT ran, PostgreSQL gave id", nextId);
const row = { id: nextId++, amount: Number(input.amount).toFixed(2), category: "Groceries", spentOn: input.spentOn };
return new Response(JSON.stringify({ data: row }), { status: 201 });
}
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
function App() {
const [amount, setAmount] = useState("2340.50");
const [list, setList] = useState([]);
const [message, setMessage] = useState("");
async function save() {
console.log("1-2. React sends the JSON");
const body = JSON.stringify({ amount, categoryId: 1, spentOn: "2026-11-02" });
const res = await fakeServer("POST", "/api/expenses", body);
const json = await res.json();
console.log("8. React got status", res.status);
if (!res.ok) return setMessage(json.error.message);
setMessage("");
setList([json.data, ...list]);
}
return (
<main>
<h1>KharchaBook</h1>
<label>
Amount (₹){" "}
<input value={amount} onChange={(e) => setAmount(e.target.value)} />
</label>{" "}
<button onClick={save}>Save</button>
{message && <p role="alert">{message}</p>}
<ul>
{list.map((e) => (
<li key={e.id}>
#{e.id} {e.category}: {rupees.format(e.amount)} on {e.spentOn}
</li>
))}
</ul>
</main>
);
}
createRoot(document.getElementById("root")).render(<App />);Click Save once, then change the amount to -5 and click again. The console shows:
1-2. React sends the JSON 3. Express received POST /api/expenses 5-6. INSERT ran, PostgreSQL gave id 2 8. React got status 201 1-2. React sends the JSON 3. Express received POST /api/expenses 4. Validation failed 8. React got status 400
The list shows #2 Groceries: ₹2,340.50 on 2026-11-02, and the second click shows "Some fields need fixing." In the real app the database is the last line of defence: even if Express forgot a check, PostgreSQL would refuse the negative amount.
PERN or MERN?
The MERN stack swaps PostgreSQL for MongoDB, a document database that stores JSON-like documents without a fixed table design. Both are good. The question is the shape of your data. Read What Is the MERN Stack? for the other side.
| Your data looks like... | Lean towards |
|---|---|
| Money, bills, marks, stock: numbers that must add up exactly | PERN |
| Many links between things (expenses to categories, orders to customers) | PERN |
| Reports with totals per month, per category, per person | PERN |
| Each record has a different shape, and you rarely join records | MERN |
PostgreSQL also stores JSON in jsonb columns, so you can keep a flexible field inside a strict table when you need one. See JSON & JSONB.
KharchaBook is about money and monthly reports, so a relational database is the natural fit. numeric(10,2) stores ₹2,340.50 exactly, a foreign key makes sure every expense points at a real category, and GROUP BY totals a month in one query.
KharchaBook: the app we build
KharchaBook (kharcha means "expense" in Hindi) tracks household expenses for a family in Pune. Each expense has an amount in rupees, a category (Groceries, Rent, Utilities and so on), the date it was spent, and an optional note. Here is the plan, section by section:
- Getting started: install the tools (Set Up Your PERN Environment) and agree on a folder layout (Project Structure for PERN Apps).
- Back end: an Express 5 REST API, then a PostgreSQL schema, queries with node-postgres, an ORM option, and login.
- Front end: a React app with Vite that lists, adds and edits expenses, with routing, forms and protected pages.
- Production: pagination and search, tests, a security checklist and deployment.
- Projects: three bigger, separate builds.
Versions used in this course, checked on npm and the official sites in November 2026: PostgreSQL 18 (18.6), Express 5.3, React 19.3, Vite 8.3 and Node.js 26 LTS.
Common mistakes
- Putting the database password in React code. Everything sent to the browser is public. Only the server reads secrets, from environment variables.
- Thinking React "connects to PostgreSQL". It does not. React calls your API; the API calls the database.
- Building SQL with string concatenation.
"... WHERE id = " + req.params.idinvites SQL injection. Always pass values as parameters. - Validating only in the browser. Anyone can send a request with curl and skip your React form. Check again on the server, and let the database constraints catch the rest.
Interview questions
1. What does each letter in PERN stand for, and where does each part run?
PostgreSQL is the database and runs on a database server. Express is the web framework and runs inside Node.js on the application server. React builds the user interface and runs in the browser. Node.js is the JavaScript runtime on the server.
2. Why should the browser never connect to the database directly?
All front-end code and network traffic can be read by the user, so database credentials in the browser would be public. A server-side API holds the credentials, checks who is asking, validates input and exposes only the operations you choose.
3. When would you pick PostgreSQL over MongoDB for a project?
When the data is relational and must stay consistent: money, inventory, bookings or anything with many links between records. PostgreSQL gives transactions, foreign keys, CHECK constraints and powerful SQL reporting, and still offers jsonb for flexible fields.
4. What is a parameterised query and why does it matter?
It sends the SQL text and the values separately, using placeholders such as $1. The database never treats the values as SQL code, so user input cannot change the query. This prevents SQL injection.
Key points
- PERN is PostgreSQL (database), Express (API framework), React (UI) and Node.js (server runtime).
- React runs in the browser; Express and Node.js run on the server; PostgreSQL stores the data.
- The browser talks only to the API over HTTP with JSON; only the server holds database credentials.
- SQL uses
snake_case, JSON usescamelCase, and the API translates in one place. - Validate on the client for a friendly experience, on the server for safety, and in the database as the final guard.
- PERN suits relational, money-like data that needs exact totals and reports.
Exercise
Write down the journey of a second request: Rohan opens KharchaBook and the app loads the list of expenses. For each of the four parts (React, Node.js, Express, PostgreSQL), write one sentence saying what it does in this request. Then write the HTTP method and path you expect React to call, and one SQL query Express might run.
Show solution
React runs fetch("/api/expenses") when the page loads and shows a loading message. Node.js runs the Express server process. Express matches GET /api/expenses, runs the query, turns each row into camelCase JSON and sends { "data": [...] } with status 200. PostgreSQL returns the rows, newest first.
SELECT e.id, e.amount, e.category_id, c.name AS category, e.spent_on, e.note, e.created_at
FROM expenses e
JOIN categories c ON c.id = e.category_id
ORDER BY e.spent_on DESC, e.id DESC;Quick Quiz
1. In a PERN app, which part runs in the user's browser?
React builds the screens in the browser; the other three run on servers.
2. Where should the PostgreSQL password live?
Anything in the browser is public, so only the server reads secrets from its environment.
3. Why do the API and the database use different naming styles?
snake_case is usual in SQL and camelCase in JavaScript; one mapping function joins them.
4. Which kind of app fits PERN best?
Money, links between tables and reports are where a relational database shines.
Learn PERN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
