Daily theme and context
On Day 11 you designed your P1's data and created it in a real database. But your app can't see that data yet: its screens still show sample data from a file. Today you build the bridge. You write your first API endpoint: a piece of server code that takes a request, asks the database with SQL, and sends the rows back as JSON. Your P1's main screen then loads its data through that endpoint, using the same four states you built on Day 7. And before the day ends, it all goes live on Vercel, so from tonight every change you push is on the internet.
This is the first day of real backend code, and it introduces two habits that every backend job expects: secrets never go in your code, and values never get glued into SQL. Both are explained in full below.
This is Week 3 of the Pilot Cohort's six-week Learn phase ("Backend"), Day 12 of 30 learning days. Day 12 starts at the Wednesday (2 Dec) 9 pm class and is due before the Thursday (3 Dec) 9 pm class; its work goes into section B of your P1 Backend Pack (Quest 3, due by Sunday 6 Dec, 11:59 pm WAT). It has four blocks, about 6 hours, done whenever suits you except the stand-up: Learn (2 hours, covered in full below), Build (2 hours, section 10: your main screen on real data, then going live), Flex (1 hour: journals, then catch-up, section 12), and the live stand-up at 9 pm WAT (1 hour).
Learning objectives
By the end of today, the learner should be able to:
- Explain what an API and an endpoint are, and what travels in a request and a response.
- Write a route handler in Next.js that runs a SQL query and returns the rows as JSON.
- Keep a connection string in
.env.local, and explain why it must never reach the browser or GitHub. - Pass values into SQL as parameters, and explain how SQL injection works and why parameters stop it.
- Load data from your own API into a React page with
fetchanduseEffect, showing the loading, empty, ready and error states. - Deploy to Vercel with an environment variable, and test the live endpoint with
curl. - Check that Supabase's automatic API can't read your tables, so your server is the only way in.
Prerequisite knowledge
From Day 11: your P1's Supabase project with your tables and test data in it, your saved database password, and your P1 app on GitHub with lib/types.ts matching your tables. From Week 2: Day 7's fetch and four states, Day 9's useState, Day 10's routes and Vercel deployment. Git Bash for the curl commands (it was installed with Git in Week 1).
TechDojo core lesson
What an API is
Your app now has two halves. The frontend is the pages that run in the user's browser. The backend runs on a server: it holds the secrets, talks to the database and decides what each user may do. The two talk through an API (application programming interface): a set of addresses on your server that accept requests and send back responses. Each address-and-method pair is one endpoint, such as GET /api/learners, "give me the list of learners".
A request and its response look like this:
REQUEST RESPONSE
GET /api/learners 200 OK
(method) (address) Content-Type: application/json
[{"id":1,"full_name":"Amina Yusuf", ...},
{"id":2,"full_name":"Chidi Okafor", ...}]
The method says what you want to do (today, GET: read; Day 13 adds the others). The status code says how it went: 200 means OK, and Day 13 covers the rest. The body carries the data, as JSON: the same format as Day 7's learners.json, except that today the server builds it from the database each time someone asks.
Why have an API at all, instead of letting the page talk to the database? Because the page runs on the user's device, where anyone can read its code. The database password must stay on the server, and so must the rules about who may see what (Days 14 and 15). And in Week 4, your phone app will use the same endpoints, so the rules live in one place.
- 1The page
fetch("/api/learners")in the browser - 2The endpoint
GETinapp/api/learners/route.ts, on the server - 3The databaseSQL through
lib/db.tsand the connection string - 4The answerRows as JSON, status
200, back to the page
The password and the rules stay on the server. The browser only ever sees the JSON.
Route handlers: endpoints in Next.js
In Next.js, an endpoint is a file called route.ts inside the app folder. Folders make the address, exactly like pages on Day 10:
app/page.tsx → the page at /
app/learners/page.tsx → the page at /learners
app/api/learners/route.ts → the endpoint at /api/learners
A route.ts exports a function named after the HTTP method it answers: GET, POST, PATCH or DELETE. Its code only ever runs on the server, never in the browser, which makes it the safe place for database code. Putting endpoints under api/ is a convention that keeps them apart from your pages.
Because route handlers run on the server, Vercel hosts your backend too. When you deploy, Vercel runs your pages and your API together, from one project. Each request starts your route handler fresh (this is called serverless), which is why the next step uses Supabase's connection pooler.
The connection string: your app's key to the database
Your app reaches the database with a connection string: one line holding the address, the database name, the username and the password. In your Supabase project, press Connect at the top of the page. Under Connection string, choose the Transaction pooler (it ends in :6543/postgres). It looks like this:
postgresql://postgres.abcdefghijklmnop:[YOUR-PASSWORD]@aws-0-eu-west-2.pooler.supabase.com:6543/postgres
Replace [YOUR-PASSWORD] (including the square brackets) with the database password you saved on Day 11. The pooler is a doorman in front of your database that shares a small number of connections between many short requests, which is what serverless needs. Use it on your laptop too, so local and live behave the same.
This string is a secret: anyone who has it can read and delete everything in your database. It goes in a file called .env.local at the top of your project, next to package.json:
DATABASE_URL=postgresql://postgres.abcdefghijklmnop:your-real-password@aws-0-eu-west-2.pooler.supabase.com:6543/postgres
Three rules:
.env.localis never committed.create-next-appalready lists.env*in.gitignore. Open.gitignoreand check the line is there before your next commit.- Never start the name with
NEXT_PUBLIC_. Next.js copies any variable with that prefix into the browser's code, where anyone can read it. Without the prefix, it stays on the server. - After changing
.env.local, stopnpm run dev(Ctrl+C) and start it again. It's only read at start-up.
Talking to Postgres from code: lib/db.ts
You need a driver: a package that speaks to Postgres for you. We use postgres, a small, popular one that lets you write plain SQL. In your project folder:
npm install postgres server-only
Then create lib/db.ts:
import "server-only";
import postgres from "postgres";
const sql = postgres(process.env.DATABASE_URL!, { prepare: false });
export default sql;
Line by line:
import "server-only"makes the build fail if any browser code ever imports this file, so the database can't leak into a page by accident.process.env.DATABASE_URLreads the variable from.env.local(on Vercel, from its settings). The!tells TypeScript "trust me, this is set".prepare: falseis needed for Supabase's transaction pooler, which doesn't support a speed-up the driver would otherwise use.export default sqllets every endpoint import one sharedsqlfunction (Day 8'sexport default).
Your first endpoint
// app/api/learners/route.ts
import { connection } from "next/server";
import sql from "@/lib/db";
export async function GET() {
await connection();
const learners = await sql`
select id, cohort_id, profile_id, full_name, phone, status
from learners
order by full_name
`;
return Response.json(learners);
}
sqlfollowed by backticks runs the SQL inside them and gives back an array of row objects, one per row, with the column names as keys: the exact shape of Day 11'sLearnertype.Response.json(learners)turns the array into JSON, sets the status to200and tells the browser it's JSON.await connection()tells Next.js to run this at the moment someone asks, never in advance while building. Without it, Next.js may try to run the query once duringnpm run buildand serve that old answer for ever, the same "built in advance" behaviour as Day 10'sloading.tsxlesson.- List the columns you need instead of writing
select *. If you later add a column that should stay private,select *would send it out without anyone noticing.
Run npm run dev and open localhost in your browser. You should see your rows as JSON.
Values in SQL: always parameters, never glued text
Soon your endpoints take values from users: an id from the address, a name from a form. Never build SQL by gluing those values into the text. Imagine an endpoint that finds one learner, written the wrong way:
// WRONG: never do this
const rows = await sql.unsafe("select * from learners where id = " + id);
If someone sends the id 1 or 1=1, the database receives select * from learners where id = 1 or 1=1. 1=1 is always true, so every learner comes back. With other text, an attacker can read other tables or delete them. This is SQL injection, one of the oldest and most common attacks on the web.
The right way:
// RIGHT: the value goes in ${ } inside sql`...`
const rows = await sql`select * from learners where id = ${id}`;
Here the driver sends the SQL and the value separately. The database treats 1 or 1=1 as one value, not as SQL, and simply refuses it: invalid input syntax for type integer: "1 or 1=1". We tested both versions on the Tracker: the glued one returned all four learners, and the parameter one returned an error. Three rules for the whole programme: put values only in ${ } inside sql`…`; never use + or a normal template string to build SQL; and never use sql.unsafe.
"… where id = " + id with 1 or 1=1 returns every learner.
sql`… where id = ${id}` sends it separately. 1 or 1=1 is refused.
Dates
A date column, such as classes.held_on, arrives in JavaScript as a full date-and-time and shows in JSON as "2026-11-16T00:00:00.000Z". To get just "2026-11-16", convert it to text in the query: select id, held_on::text as held_on, topic from classes. timestamptz columns, such as created_at, are fine as they come.
Showing the data on a page: useEffect
The page asks the API for data once, when it first appears on screen. In React, "do this after the component appears" is useEffect. Here is the Tracker's learner list, with Day 7's four states:
// components/LearnerList.tsx
"use client";
import { useEffect, useState } from "react";
import type { Learner } from "@/lib/types";
async function getLearners(): Promise<Learner[]> {
const response = await fetch("/api/learners");
if (!response.ok) {
throw new Error(`The server answered ${response.status}`);
}
return response.json();
}
export default function LearnerList() {
const [learners, setLearners] = useState<Learner[]>([]);
const [status, setStatus] = useState<"loading" | "ready" | "error">("loading");
function load() {
getLearners()
.then((rows) => {
setLearners(rows);
setStatus("ready");
})
.catch(() => setStatus("error"));
}
useEffect(() => {
load();
}, []);
if (status === "loading") {
return <p aria-live="polite">Loading learners…</p>;
}
if (status === "error") {
return (
<div>
<p>Couldn't load the learners. Check your connection and try again.</p>
<button onClick={() => { setStatus("loading"); load(); }}>Try again</button>
</div>
);
}
if (learners.length === 0) {
return <p>No learners yet.</p>;
}
return (
<ul>
{learners.map((learner) => (
<li key={learner.id}>{learner.full_name}</li>
))}
</ul>
);
}
useEffect(() => { … }, [])runs the function once, after the component first appears. The empty[]at the end means "only once"; without it, it would run after every redraw and fetch again and again.getLearnersis Day 7's fetch pattern: checkresponse.ok, otherwisethrow, so the error state shows. The address is/api/learnerswith no localhost, so the same code works on your laptop and on Vercel.- The four states:
loadingfirst,errorwith a working Try again button, an empty message when there are no rows, and the list when it's ready. It's the same idea as Day 7, now in React state (Day 9). - It's a client component (
"use client") because it uses state and effects. The page that shows it,app/learners/page.tsx, stays a server component and simply renders<LearnerList />(Day 10).
Your screens can stay as they are. Instead of importing sample data, the component now fetches it, and because Day 11's types use the database's column names, the rest of the code doesn't change.
Going live with a secret
Your .env.local file isn't in GitHub, so Vercel doesn't have your connection string. You give it to Vercel separately:
- Import your P1 repository into Vercel, the same steps as Day 10, if you haven't already.
- In the Vercel project, open Settings, then Environment Variables. Add
DATABASE_URLwith the same value as in.env.local, for all environments, and save. - Open Deployments, choose the latest one's … menu, and Redeploy. Environment variables are only read when the app is built, so a deployment made before you added the variable doesn't have it.
- Open your-app.vercel.app: the same JSON, now from the internet.
- 1
.env.localOn your laptop, never committed - 2Vercel settingsEnvironment Variables: add
DATABASE_URL - 3RedeployVariables are read when the app is built
- 4Live endpointSame JSON, from the internet
Testing an endpoint with curl
Developers test endpoints without a browser, using curl, a command that sends a request and prints the response. In Git Bash (not PowerShell, where curl is a different command):
curl -i https://your-app.vercel.app/api/learners
-i also shows the status line (HTTP/2 200) and the headers, including content-type: application/json. From Day 13 you test every endpoint this way before building any screen for it. (Many teams use a tool called Postman for the same job; curl needs no installing and works the same on every computer and server.)
Locking the back door: proving your tables are private
Supabase gives every project an automatic web API, which anyone can call with your project's publishable key (a key that's allowed to be public, because it goes into apps). On Day 11, every schema ended with alter table … enable row level security;. With row level security on and no rules added, that automatic API returns nothing from your tables. Your own server isn't affected: it signs in with the database password, as the tables' owner.
Check it today. In Supabase, open Project Settings, then API Keys, and copy the publishable key (it starts with sb_publishable_). Your project's address is on the same page or under Connect (it looks like abcdefghijklmnop.supabase.co). In Git Bash:
curl "https://abcdefghijklmnop.supabase.co/rest/v1/learners?select=*" -H "apikey: sb_publishable_your-key"
You should get []: an empty list, though your table has rows. If you see your rows, row level security is off for that table: run alter table your_table enable row level security; in the SQL Editor and try again. From now on, the only way to your data is through your endpoints, and Days 14 and 15 put the rules there.
app.get("/api/learners", async (req, res) => {
const learners = await sql`select id, full_name from learners order by full_name`;
res.json(learners);
});
Same method, same address, same SQL, same JSON. Only the wrapping differs: Express registers routes in code with app.get(...), where Next.js uses folders and files. If an interviewer asks about Express routes, you can explain them through what you built today.
How the Tracker maps to your P1:
| Tracker | Your P1 |
|---|---|
GET /api/learners in app/api/learners/route.ts | GET /api/<your-main-thing>, such as app/api/orders/route.ts |
select id, cohort_id, … from learners order by full_name | Your main table's columns, in a sensible order (newest first is often best: order by created_at desc) |
components/LearnerList.tsx | A list component for your main screen |
Learner in lib/types.ts | Your main table's type from Day 11 |
Video resource
About 11 minutes together. From the Fireship video, watch only the first 2 minutes: the 100-second overview of what an API is and the words you'll hear all week (endpoint, method, status code, JSON). The rest of that video builds an API in Express; it's optional, and Day 13 comes back to it. The Computerphile video (9 minutes) shows an injection attack on a test website, step by step, and why gluing text into SQL causes it.
Guided viewing questions:
- In your own words, what does an API endpoint receive, and what does it send back?
- In the injection video, what did the attacker type, and why did the website's code let it through?
- How would
${ }parameters insql`…`have stopped that attack?
Reading resource
Read the opening sections, up to and including the HTTP methods. Skip caching for now.
Next.js, "Environment Variables"nextjs.orgRead "Loading environment variables" and "Bundling environment variables for the browser" (the NEXT_PUBLIC_ rule).
Guided reading questions:
- Which file name and which function name make an endpoint that answers
GETrequests? - What happens to a variable whose name starts with
NEXT_PUBLIC_? Why does that make it the wrong place for a database password? - Which file should hold your local secrets, and why isn't it committed?
Interactive exercise
Today's exercise is your P1's first endpoint. Use the table at the end of section 4 for your names.
- 10 min The connection string. In Supabase, press Connect, copy the Transaction pooler string, put your password in it, and save it as
DATABASE_URLin.env.localat the top of your P1 project. Check that.gitignorehas a.env*line. Rungit status:.env.localmust not be listed. - 10 min
lib/db.ts. Runnpm install postgres server-onlyand writelib/db.tsexactly as in section 4. Type it yourself; don't paste it. - 10 min Your first endpoint. Write
app/api/<your-main-thing>/route.tswith aGETthat selects your main table's columns. Startnpm run devand open the endpoint in your browser. Then, in Git Bash, runcurl -i http://localhost:3000/api/<your-main-thing>and find the status line and thecontent-typeheader. - 10 min See injection for yourself, safely. In the Supabase SQL Editor, run
select * from <your-main-table> where id = 1;, thenselect * from <your-main-table> where id = 1 or 1=1;. The second returns every row: that's exactly the SQL a glued-together query would send if a user typed1 or 1=1. In your notes, explain in two sentences why${id}insql`…`can't be tricked this way.
AI-assisted learning prompt
Use your AI assistant to check your understanding, not to write the code:
Here is my lib/db.ts and my first route handler: [paste both, with no password or connection string in them]. Don't rewrite them. Ask me five questions, one at a time, that check whether I understand what each line does and why it's there, including where the code runs and what keeps my database password safe. After each answer, tell me what I got right and what I missed.
Log it in your AI-use journal: which questions you got wrong, and what you now understand.
Knowledge check
A self-check: do it without notes and without AI, then compare with section 4. It isn't submitted.
- What's the difference between an API and an endpoint? Give one endpoint from your P1.
- Which file makes the endpoint
GET /api/ordersin Next.js, and what must it export? - Where does the connection string live on your laptop, and where on Vercel? Why not in your code?
- What would happen if you named the variable
NEXT_PUBLIC_DATABASE_URL? - A user sends the id
5 or 1=1. What happens withsql.unsafe("… where id = " + id), and what happens withsql`… where id = ${id}`? - Why does the
useEffectinLearnerListend with[]? - Your endpoint works on your laptop but answers
500on Vercel. Name the most likely cause and how to fix it.
Build block: your main screen on real data, then live
If it breaks
Find your error here first. If it isn't here, post the exact message in the cohort group (and never your connection string or password).
password authentication failed for user "postgres.…": the password in your connection string is wrong, or the square brackets from[YOUR-PASSWORD]are still there. If you've lost the password, reset it in Project Settings, Database, and update.env.local(and Vercel).getaddrinfo ENOTFOUND,ENETUNREACHorconnect ETIMEDOUT, with port5432: you copied the Direct connection string. Use the Transaction pooler string, which ends in:6543/postgres.prepared statement … already existsor… does not exist:{ prepare: false }is missing fromlib/db.ts.- Your password has
@,#,/or?in it, and the connection fails oddly: those characters break the connection string. Reset the password to letters and numbers only. DATABASE_URLseems empty, orInvalid URL:.env.localmust sit next topackage.json, not insideapporlib, and the line has no spaces around=and no quotes. Restartnpm run devafter any change.Module not found: Can't resolve 'postgres': runnpm install postgres server-onlyinside your project folder (the one withpackage.json).This module cannot be imported from a Client Component module: a"use client"file importslib/db.ts. Browser code must never touch the database: fetch your API instead. That'sserver-onlydoing its job.relation "orders" does not exist: the table name in your SQL doesn't match the one in Supabase, or you ran the endpoint against a project without your schema. Check the Table Editor.- The page stays on "Loading…" for ever: the
fetchaddress is wrong (it must start with/api/), orload()isn't called inuseEffect. Open the browser's developer tools: the Console shows errors, and the Network tab shows what the request got back. - Works on your laptop,
500on Vercel:DATABASE_URLisn't set on Vercel, or you didn't redeploy after adding it. In Vercel, the project's Logs page shows the real error message from your server. - Dates show as
2026-11-16T00:00:00.000Z: select the column asyour_date::text as your_date. - In PowerShell,
curlasks about "Uri" or prints a table: that's PowerShell's own command with the same name. Runcurlin Git Bash. - The locked-door check shows your rows: row level security is off on that table. Run
alter table <name> enable row level security;and check again. - Everything fails after a quiet week: free Supabase projects pause after 7 days without use. Open the project and press Restore.
Flex hour: journals, then catch-up
- Journals first (section 14).
- Then catch up, in this order: anything left from Day 11's data model, then today's live deploy.
- Optional: SQLBolt lessons 1 to 6 (sqlbolt.com), for more practice writing queries.
Deliverables and submission criteria
Write section B (First endpoint, live) of your P1 Backend Pack, handed in with the whole Pack by Sunday 6 Dec, 11:59 pm WAT. Section B should have:
0 of 7 ticked Ticks are saved on this device only.
Daily journal reflection
Add today's entry to your three running journals:
- Engineering journal: Which error took longest to fix today, and how did you find the cause? Estimate vs actual: your estimate for today against the time it took.
- AI-use journal: The understanding-check prompt: which questions you got wrong, and what you learned. Anything you asked the AI to write, and what you changed.
- Curriculum journal: Was anything on this page unclear, or did you have to look anything up elsewhere? Say exactly what, so we can add it.