Skip to content
Qyubie Learn
Web Development courseLesson 16 of 20 · tap to see all lessons

Web Development · Beginner

Database Integration and CRUD: Supabase PostgreSQL in Next.js with Forms, Validation, and Errors

Connect a Next.js app to Supabase PostgreSQL, build database-driven forms with server-side validation, and create, read, update, and delete records while handling errors.

  • Qyubie Learn Editorial Team
  • Published
  • 22 min read

Includes 1 exercise and 2 quick checks you can do right here.

In lesson 15 the students lived in an array that vanished every time the server restarted. Real apps keep data in a database. In this lesson you'll connect the class portal to Supabase PostgreSQL (set up in lesson 9), then build the four operations every data app needs, CRUD: Create, Read, Update, and Delete, with forms that validate input and explain errors.

By the end of this lesson you will be able to:

  • connect a Next.js app to Supabase with environment variables,
  • create a table with constraints, row level security, and grants,
  • read rows in a server component and show loading, empty, and error states,
  • build forms that save through Server Actions, with server-side validation,
  • update and delete records, and
  • turn database errors into messages users understand.

Connecting Next.js to Supabase

In your Next.js project (lesson 14), install the two Supabase packages:

npm install @supabase/supabase-js @supabase/ssr

@supabase/supabase-js is the client library; @supabase/ssr makes it work with cookies on the server, which lesson 17 needs for logins.

Next, copy your project's URL and publishable key (lesson 9; both are in your project's API settings in the Supabase dashboard) into a file named .env.local in the project root:

# .env.local
NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_your_key_here

Next.js loads .env.local into process.env automatically. Restart npm run dev after editing it. The default .gitignore already excludes .env files, so they never reach GitHub; lesson 17 explains what the NEXT_PUBLIC_ prefix means for security.

Now a small helper that creates a Supabase client on the server. It's the version from Supabase's official Next.js starter, plus one line, await connection():

// lib/supabase/server.ts
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import { connection } from "next/server";

export async function createClient() {
  await connection();
  const cookieStore = await cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options),
            );
          } catch {
            // Called from a Server Component, where cookies can't be set.
            // Safe to ignore when proxy.ts refreshes sessions (lesson 17).
          }
        },
      },
    },
  );
}

await connection() tells Next.js that what follows belongs to one visitor's request, so it must never be prepared ahead of time and shared. Without it, the recommended Next.js defaults try to prepare pages early, and the server log fills with "encountered the unstable value Date.now()" errors from inside the Supabase client.

Two habits from Supabase's docs: call createClient() inside each function that needs it (never store one client in a global variable shared by all users), and keep the ! after the variable names only once you've set them, since it tells TypeScript "this is definitely set".

Creating the table

Open the SQL Editor in the Supabase dashboard and run this script. It's worth saving in your project too (for example supabase/schema.sql) so teammates can create the same database:

create table public.students (
  id bigint generated always as identity primary key,
  student_no text not null unique,
  full_name text not null,
  course text not null check (course in ('BSCS', 'BSIT')),
  year smallint not null check (year between 1 and 4),
  email text not null,
  created_at timestamptz not null default now()
);

alter table public.students enable row level security;

grant select, insert, update, delete on table public.students to anon, authenticated;

-- PRACTICE ONLY: lesson 17 replaces these four policies.
create policy "Practice: anyone can read students"
on public.students for select to anon, authenticated using ( true );

create policy "Practice: anyone can add students"
on public.students for insert to anon, authenticated with check ( true );

create policy "Practice: anyone can edit students"
on public.students for update to anon, authenticated using ( true ) with check ( true );

create policy "Practice: anyone can delete students"
on public.students for delete to anon, authenticated using ( true );

insert into public.students (student_no, full_name, course, year, email) values
  ('2023-0001', 'Ana Reyes', 'BSCS', 3, 'ana@example.com'),
  ('2024-0002', 'Ben Cruz', 'BSIT', 2, 'ben@example.com');

What each part does:

  • Constraints are your last line of defense. unique stops duplicate student numbers, and the check rules reject a course or year your app doesn't support, even if a bug in your code lets bad data through.
  • grant lets the Data API's roles reach the table at all (see lesson 9). RLS then decides which rows each request may touch.
  • The four "Practice" policies let anyone with your publishable key read and change every row. That's fine for learning on test data, and dangerous for anything real. Lesson 17 replaces them with policies tied to logged-in users. Don't deploy an app with them.

Reading: listing records

Keep database code out of your pages: a small data module makes each query easy to find and reuse. Every Supabase query returns { data, error } instead of throwing, so check error every time:

// lib/students.ts
import { createClient } from "@/lib/supabase/server";

export type Student = {
  id: number;
  student_no: string;
  full_name: string;
  course: string;
  year: number;
  email: string;
};

const COLUMNS = "id, student_no, full_name, course, year, email";

export async function getStudents(): Promise<Student[]> {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("students")
    .select(COLUMNS)
    .order("full_name");

  if (error) {
    throw new Error(`Could not load students: ${error.message}`);
  }
  return data;
}

export async function getStudent(id: number): Promise<Student | null> {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("students")
    .select(COLUMNS)
    .eq("id", id)
    .maybeSingle();

  if (error) {
    throw new Error(`Could not load student ${id}: ${error.message}`);
  }
  return data;
}
  • .select(COLUMNS) names the columns you need, like SELECT id, ... in SQL.
  • .order("full_name") sorts; .eq("id", id) is WHERE id = ....
  • .maybeSingle() returns one row or null when there's none. (.single() treats "no row" as an error.)

The list page follows lesson 15's pattern: a server component inside <Suspense> for the loading state, an empty state, and error.tsx for failures:

// app/students/page.tsx
import Link from "next/link";
import { Suspense } from "react";
import { getStudents } from "@/lib/students";
import { deleteStudent } from "./actions";

async function StudentTable() {
  const students = await getStudents();

  if (students.length === 0) {
    return <p className="mt-6 text-gray-500">No students yet. Add the first one.</p>;
  }

  return (
    <ul className="mt-6 divide-y rounded-lg bg-white shadow">
      {students.map((s) => (
        <li key={s.id} className="flex flex-wrap items-center justify-between gap-2 p-4">
          <div>
            <p className="font-semibold">{s.full_name}</p>
            <p className="text-sm text-gray-500">
              {s.student_no} · {s.course} {s.year} · {s.email}
            </p>
          </div>
          <div className="flex gap-2">
            <Link href={`/students/${s.id}/edit`} className="rounded-lg border px-3 py-1.5 text-sm">
              Edit
            </Link>
            <form action={deleteStudent.bind(null, s.id)}>
              <button className="rounded-lg border border-red-200 px-3 py-1.5 text-sm text-red-700">
                Delete
              </button>
            </form>
          </div>
        </li>
      ))}
    </ul>
  );
}

export default function StudentsPage() {
  return (
    <section>
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">Students</h1>
        <Link href="/students/new" className="rounded-lg bg-violet-600 px-4 py-2 text-white">
          Add student
        </Link>
      </div>
      <Suspense fallback={<p className="mt-6 text-gray-500">Loading students...</p>}>
        <StudentTable />
      </Suspense>
    </section>
  );
}
// app/students/error.tsx
"use client";

export default function StudentsError({ error, retry }: { error: unknown; retry: () => void }) {
  console.error(error);

  return (
    <div role="alert" className="rounded-lg bg-red-50 p-4 text-red-700">
      <p>We couldn't reach the database. Check your connection and try again.</p>
      <button onClick={() => retry()} className="mt-2 font-semibold underline">
        Try again
      </button>
    </div>
  );
}

Creating and updating: forms with Server Actions

In lesson 15, a client sent JSON to a Route Handler. Next.js has a shorter path for your own forms: a Server Action, an async function marked "use server" that runs on the server when a form is submitted. You pass it to the form's action, and Next.js handles the request for you.

All the actions for students go in one file. The "use server" line at the top makes every exported function a Server Action:

// app/students/actions.ts
"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { validateStudent, type FieldErrors, type StudentInput } from "@/lib/validate";

export type FormState = {
  errors?: FieldErrors;
  message?: string;
  values?: Record<string, string>;
};

function toRow(input: StudentInput) {
  return {
    student_no: input.studentNo,
    full_name: input.fullName,
    course: input.course,
    year: input.year,
    email: input.email,
  };
}

function readForm(formData: FormData) {
  const values: Record<string, string> = {};
  for (const [key, value] of formData) {
    if (typeof value === "string") values[key] = value;
  }
  return values;
}

function saveFailed(error: { code?: string; message: string }): FormState {
  if (error.code === "23505") {
    return { errors: { studentNo: "That student number is already used." } };
  }
  console.error("Supabase error:", error);
  return { message: "We couldn't save the student. Please try again." };
}

export async function createStudent(_state: FormState, formData: FormData): Promise<FormState> {
  const values = readForm(formData);
  const result = validateStudent(values);
  if (!result.ok) {
    return { errors: result.errors, values };
  }

  const supabase = await createClient();
  const { error } = await supabase.from("students").insert(toRow(result.data));
  if (error) {
    return { ...saveFailed(error), values };
  }

  revalidatePath("/students");
  redirect("/students");
}

export async function updateStudent(
  id: number,
  _state: FormState,
  formData: FormData,
): Promise<FormState> {
  const values = readForm(formData);
  const result = validateStudent(values);
  if (!result.ok) {
    return { errors: result.errors, values };
  }

  const supabase = await createClient();
  const { error } = await supabase.from("students").update(toRow(result.data)).eq("id", id);
  if (error) {
    return { ...saveFailed(error), values };
  }

  revalidatePath("/students");
  redirect("/students");
}

export async function deleteStudent(id: number) {
  const supabase = await createClient();
  const { error } = await supabase.from("students").delete().eq("id", id);
  if (error) {
    throw new Error(`Could not delete student ${id}: ${error.message}`);
  }
  revalidatePath("/students");
}

Step by step, createStudent:

  1. Reads the form into plain strings.
  2. Validates on the server with validateStudent from lesson 15. Browser checks (like required) are nice for users, but anyone can skip them, so the server always checks again.
  3. Inserts the row. The table uses snake_case column names, so toRow converts.
  4. Handles errors. 23505 is PostgreSQL's code for a unique violation (a duplicate student number), which becomes a message on that field. Anything else is logged on the server, and the user gets a calm, general message without database details.
  5. revalidatePath("/students") tells Next.js the list changed, then redirect sends the user back to it. redirect must come last: code after it never runs.

When validation fails, the action returns a state object instead of redirecting: the errors, plus the values the user typed, so the form can show them again.

The form component

The form uses React's useActionState hook. It calls the action with the previous state and the form data, and gives you the latest returned state and a pending flag. That needs a client component, and the same form works for both adding and editing:

// app/students/StudentForm.tsx
"use client";

import { useActionState } from "react";
import type { Student } from "@/lib/students";
import type { FormState } from "./actions";

type Props = {
  action: (state: FormState, formData: FormData) => Promise<FormState>;
  student?: Student;
  submitLabel: string;
};

export default function StudentForm({ action, student, submitLabel }: Props) {
  const [state, formAction, pending] = useActionState(action, {});
  const values = state.values;

  return (
    <form action={formAction} noValidate className="mt-6 grid gap-4 rounded-lg bg-white p-6 shadow sm:grid-cols-2">
      <Field
        label="Student no."
        name="studentNo"
        placeholder="2025-0001"
        defaultValue={values?.studentNo ?? student?.student_no}
        error={state.errors?.studentNo}
      />
      <Field
        label="Full name"
        name="fullName"
        defaultValue={values?.fullName ?? student?.full_name}
        error={state.errors?.fullName}
      />
      <label className="grid gap-1 text-sm font-medium">
        Course
        <select
          name="course"
          key={values?.course}
          defaultValue={values?.course ?? student?.course ?? "BSCS"}
          className="h-11 rounded-lg border px-3"
        >
          <option>BSCS</option>
          <option>BSIT</option>
        </select>
        {state.errors?.course && <span className="text-red-700">{state.errors.course}</span>}
      </label>
      <Field
        label="Year"
        name="year"
        type="number"
        defaultValue={values?.year ?? student?.year?.toString()}
        error={state.errors?.year}
      />
      <Field
        label="Email"
        name="email"
        type="email"
        defaultValue={values?.email ?? student?.email}
        error={state.errors?.email}
      />

      {state.message && (
        <p role="alert" className="rounded-lg bg-red-50 p-3 text-sm text-red-700 sm:col-span-2">
          {state.message}
        </p>
      )}

      <div className="sm:col-span-2">
        <button
          disabled={pending}
          className="h-11 rounded-lg bg-violet-600 px-5 font-semibold text-white disabled:opacity-60"
        >
          {pending ? "Saving..." : submitLabel}
        </button>
      </div>
    </form>
  );
}

function Field({
  label,
  name,
  type = "text",
  placeholder,
  defaultValue,
  error,
}: {
  label: string;
  name: string;
  type?: string;
  placeholder?: string;
  defaultValue?: string;
  error?: string;
}) {
  return (
    <label className="grid gap-1 text-sm font-medium">
      {label}
      <input
        name={name}
        type={type}
        placeholder={placeholder}
        defaultValue={defaultValue}
        aria-invalid={error ? true : undefined}
        className="h-11 rounded-lg border px-3"
      />
      {error && <span className="text-red-700">{error}</span>}
    </label>
  );
}
  • The inputs are uncontrolled (defaultValue, not value), since the action reads them from the submitted form data.
  • After a form action finishes, React resets the form to its default values. That's why the action returns values: they become the new defaults, so the user's typing survives an error. A <select> only reads defaultValue when it first appears, so key={values?.course} makes React create it again with the returned value.
  • pending disables the button and changes its text while saving, so users don't click twice.
  • aria-invalid and role="alert" let screen readers announce problems.

The "add" page just passes the create action:

// app/students/new/page.tsx
import StudentForm from "../StudentForm";
import { createStudent } from "../actions";

export default function NewStudentPage() {
  return (
    <section>
      <h1 className="text-2xl font-bold">Add a student</h1>
      <StudentForm action={createStudent} submitLabel="Add student" />
    </section>
  );
}

The edit page loads the student, shows Next.js's "not found" page for a missing ID, and binds the ID to the update action: updateStudent.bind(null, student.id) makes a new function with id already filled in, so the form calls it with just the state and form data:

// app/students/[id]/edit/page.tsx
import { notFound } from "next/navigation";
import { getStudent } from "@/lib/students";
import StudentForm from "../../StudentForm";
import { updateStudent } from "../../actions";

export default async function EditStudentPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const student = await getStudent(Number(id));

  if (!student) {
    notFound();
  }

  return (
    <section>
      <h1 className="text-2xl font-bold">Edit {student.full_name}</h1>
      <StudentForm
        action={updateStudent.bind(null, student.id)}
        student={student}
        submitLabel="Save changes"
      />
    </section>
  );
}
// app/students/[id]/edit/loading.tsx
export default function Loading() {
  return <p className="text-gray-500">Loading student...</p>;
}

Deleting

Deleting uses the same idea in its simplest form. In the list page above, each row has:

<form action={deleteStudent.bind(null, s.id)}>
  <button>Delete</button>
</form>

The bound action runs on the server, deletes the row with .delete().eq("id", id), and calls revalidatePath, so the list re-renders without that student. Always filter a delete or update (.eq("id", id)): without a filter it would affect every row the policies allow. For real apps, ask the user to confirm first, for example with a small client component that calls confirm() before submitting, or a dialog.

Handling database errors

Errors will happen: the network drops, a key is wrong, a rule rejects a row. Plan for them:

What you seeUsual causeWhat to do
a query returns [] but the table has rowsRLS is on and no policy allows the readadd the right policy (lesson 9)
error.code is 42501, "permission denied for table"the role has no grant on the tablerun the grant statement
23505a unique value already existsshow a message on that field
23514a check constraint failedyour validation missed a case; fix it and show a message
error.message mentions fetch or the networkwrong URL in .env.local, or no internetcheck the variables and restart the dev server

Good habits:

  • Check error after every query. Supabase doesn't throw, so an unchecked error silently gives you data: null.
  • Show users a short, helpful message; log the full error on the server. Database messages can reveal table names and rules.
  • Keep the user's input after an error, so they can fix one field instead of retyping everything.
  • Validate in your code and constrain in the database. Validation gives friendly messages; constraints guarantee the data stays correct.

Quick check

An insert returns an error with code 23505. What does it mean, and what should the user see?

Quick check

Why does createStudent validate the data when the form could use HTML required and type="email"?

Practice the SQL behind each CRUD step here. The table below is the same students table in the browser's SQLite:

Exercise · SQL

Update and delete safely

Ben moved up to year 3, and the student with number 2025-0009 withdrew. Write an UPDATE (by id) and a DELETE (by student_no), then the SELECT that lists full_name and year ordered by full_name.

Hint

UPDATE students SET year = 3 WHERE id = 2; then DELETE FROM students WHERE student_no = '2025-0009'; Both need a WHERE.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

UPDATE students SET year = 3 WHERE id = 2;
DELETE FROM students WHERE student_no = '2025-0009';
SELECT full_name, year FROM students ORDER BY full_name;

Common mistakes

  • Forgetting to restart npm run dev after editing .env.local.
  • Not checking error, then crashing on data being null.
  • An update or delete without .eq(...).
  • Using .single() for a row that might not exist; use .maybeSingle() and handle null.
  • Forgetting revalidatePath, so the list still shows old data after saving.
  • Putting code after redirect(); it never runs.
  • Leaving the "Practice" policies in a real app. Lesson 17 fixes them.

Summary

  • Install @supabase/supabase-js and @supabase/ssr, put the URL and publishable key in .env.local, and create the client inside each server function.
  • Create tables with constraints, enable RLS, grant access, and add policies.
  • Every query returns { data, error }: select, insert, update().eq(), delete().eq(), order, maybeSingle.
  • Server Actions ("use server") handle form submits: validate, save, then revalidatePath and redirect; return errors and values when something's wrong. useActionState shows them, with a pending flag.
  • Translate database errors (like 23505) into helpful messages, and log the details on the server.

Next: authentication and security. Users will sign up and log in, and the database will only let each user see and change their own records.

References and further reading