TechDojoPilot Cohort Week 3 · Day 12

Pilot CohortPhase 1Week 3Day 12

Your First API Endpoint: Connecting Next.js to PostgreSQL, and Going Live

Your day, about 6 hours

  1. Learn2 hSections 4 to 9
  2. Build2 hMain screen on real data, then live, section 10
  3. Flex1 hJournals, then catch-up, section 12
  4. Stand-up1 hLive, 9 pm WAT
01

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).

02

Learning objectives

By the end of today, the learner should be able to:

  1. Explain what an API and an endpoint are, and what travels in a request and a response.
  2. Write a route handler in Next.js that runs a SQL query and returns the rows as JSON.
  3. Keep a connection string in .env.local, and explain why it must never reach the browser or GitHub.
  4. Pass values into SQL as parameters, and explain how SQL injection works and why parameters stop it.
  5. Load data from your own API into a React page with fetch and useEffect, showing the loading, empty, ready and error states.
  6. Deploy to Vercel with an environment variable, and test the live endpoint with curl.
  7. Check that Supabase's automatic API can't read your tables, so your server is the only way in.
03

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).

04

TechDojo core lesson

35 minutes

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.

  1. 1The pagefetch("/api/learners") in the browser
  2. 2The endpointGET in app/api/learners/route.ts, on the server
  3. 3The databaseSQL through lib/db.ts and the connection string
  4. 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.local is never committed. create-next-app already lists .env* in .gitignore. Open .gitignore and 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, stop npm 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_URL reads the variable from .env.local (on Vercel, from its settings). The ! tells TypeScript "trust me, this is set".
  • prepare: false is needed for Supabase's transaction pooler, which doesn't support a speed-up the driver would otherwise use.
  • export default sql lets every endpoint import one shared sql function (Day 8's export 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);
}
  • sql followed 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's Learner type.
  • Response.json(learners) turns the array into JSON, sets the status to 200 and 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 during npm run build and serve that old answer for ever, the same "built in advance" behaviour as Day 10's loading.tsx lesson.
  • 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.

Glued into the textThe value becomes SQL

"… where id = " + id with 1 or 1=1 returns every learner.

Passed as a parameterThe value stays a value

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.
  • getLearners is Day 7's fetch pattern: check response.ok, otherwise throw, so the error state shows. The address is /api/learners with no localhost, so the same code works on your laptop and on Vercel.
  • The four states: loading first, error with 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:

  1. Import your P1 repository into Vercel, the same steps as Day 10, if you haven't already.
  2. In the Vercel project, open Settings, then Environment Variables. Add DATABASE_URL with the same value as in .env.local, for all environments, and save.
  3. 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.
  4. Open your-app.vercel.app: the same JSON, now from the internet.
  1. 1.env.localOn your laptop, never committed
  2. 2Vercel settingsEnvironment Variables: add DATABASE_URL
  3. 3RedeployVariables are read when the app is built
  4. 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:

TrackerYour P1
GET /api/learners in app/api/learners/route.tsGET /api/<your-main-thing>, such as app/api/orders/route.ts
select id, cohort_id, … from learners order by full_nameYour main table's columns, in a sensible order (newest first is often best: order by created_at desc)
components/LearnerList.tsxA list component for your main screen
Learner in lib/types.tsYour main table's type from Day 11
05

Video resource

15 minutes
Fireship, "RESTful APIs in 100 Seconds" Open on YouTube
Computerphile, "Hacking Websites with SQL Injection" Open on YouTube

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:

  1. In your own words, what does an API endpoint receive, and what does it send back?
  2. In the injection video, what did the attacker type, and why did the website's code let it through?
  3. How would ${ } parameters in sql`…` have stopped that attack?
06

Reading resource

15 minutes
Next.js, "Route Handlers"nextjs.org

Read the opening sections, up to and including the HTTP methods. Skip caching for now.

Next.js, "Environment Variables"nextjs.org

Read "Loading environment variables" and "Bundling environment variables for the browser" (the NEXT_PUBLIC_ rule).

Guided reading questions:

  1. Which file name and which function name make an endpoint that answers GET requests?
  2. What happens to a variable whose name starts with NEXT_PUBLIC_? Why does that make it the wrong place for a database password?
  3. Which file should hold your local secrets, and why isn't it committed?
07

Interactive exercise

40 minutes

Today's exercise is your P1's first endpoint. Use the table at the end of section 4 for your names.

  1. 10 min The connection string. In Supabase, press Connect, copy the Transaction pooler string, put your password in it, and save it as DATABASE_URL in .env.local at the top of your P1 project. Check that .gitignore has a .env* line. Run git status: .env.local must not be listed.
  2. 10 min lib/db.ts. Run npm install postgres server-only and write lib/db.ts exactly as in section 4. Type it yourself; don't paste it.
  3. 10 min Your first endpoint. Write app/api/<your-main-thing>/route.ts with a GET that selects your main table's columns. Start npm run dev and open the endpoint in your browser. Then, in Git Bash, run curl -i http://localhost:3000/api/<your-main-thing> and find the status line and the content-type header.
  4. 10 min See injection for yourself, safely. In the Supabase SQL Editor, run select * from <your-main-table> where id = 1;, then select * 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 typed 1 or 1=1. In your notes, explain in two sentences why ${id} in sql`…` can't be tricked this way.
08

AI-assisted learning prompt

Use your AI assistant to check your understanding, not to write the code:

Prompt

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.

09

Knowledge check

15 minutes

A self-check: do it without notes and without AI, then compare with section 4. It isn't submitted.

  1. What's the difference between an API and an endpoint? Give one endpoint from your P1.
  2. Which file makes the endpoint GET /api/orders in Next.js, and what must it export?
  3. Where does the connection string live on your laptop, and where on Vercel? Why not in your code?
  4. What would happen if you named the variable NEXT_PUBLIC_DATABASE_URL?
  5. A user sends the id 5 or 1=1. What happens with sql.unsafe("… where id = " + id), and what happens with sql`… where id = ${id}`?
  6. Why does the useEffect in LearnerList end with []?
  7. Your endpoint works on your laptop but answers 500 on Vercel. Name the most likely cause and how to fix it.
10

Build block: your main screen on real data, then live

2 hours
11

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, ENETUNREACH or connect ETIMEDOUT, with port 5432: you copied the Direct connection string. Use the Transaction pooler string, which ends in :6543/postgres.
  • prepared statement … already exists or … does not exist: { prepare: false } is missing from lib/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_URL seems empty, or Invalid URL: .env.local must sit next to package.json, not inside app or lib, and the line has no spaces around = and no quotes. Restart npm run dev after any change.
  • Module not found: Can't resolve 'postgres': run npm install postgres server-only inside your project folder (the one with package.json).
  • This module cannot be imported from a Client Component module: a "use client" file imports lib/db.ts. Browser code must never touch the database: fetch your API instead. That's server-only doing 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 fetch address is wrong (it must start with /api/), or load() isn't called in useEffect. Open the browser's developer tools: the Console shows errors, and the Network tab shows what the request got back.
  • Works on your laptop, 500 on Vercel: DATABASE_URL isn'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 as your_date::text as your_date.
  • In PowerShell, curl asks about "Uri" or prints a table: that's PowerShell's own command with the same name. Run curl in 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.
12

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.
13

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.

14

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.