Web Development courseLesson 17 of 20 · tap to see all lessons
Web Development · Beginner
Authentication and Security Basics: Supabase Auth, Protected Pages, Validation, Secrets, and RLS
Add sign-up, login, and logout with Supabase Auth, protect pages and Server Actions, validate input, keep secrets out of the browser, and lock data down with RLS.
- Qyubie Learn Editorial Team
- Published
- 26 min read
Includes 1 exercise and 3 quick checks you can do right here.
Right now anyone who opens the class portal can read, change, and delete every student record. That's fine on a practice database and a disaster anywhere else. This lesson adds accounts and then closes the gaps one by one: who you are, what you may do, what input you accept, where secrets live, and what the database itself allows.
By the end of this lesson you will be able to:
- explain authentication, authorization, and sessions,
- add sign-up, login, and logout with Supabase Auth,
- protect pages and Server Actions so only logged-in users get in,
- validate and safely display user input,
- keep keys and secrets out of the browser and out of Git, and
- write row level security policies so each user can reach only their own data.
Authentication and authorization
Two words that sound alike and mean different things:
| Question it answers | Example | |
|---|---|---|
| Authentication (authn) | Who are you? | logging in with email and password |
| Authorization (authz) | What are you allowed to do? | a teacher can edit only the students they added |
After you log in, the server gives your browser a session, stored in a cookie, so you don't have to type your password on every page. Each request sends the cookie, and the server checks it to know who you are.
Supabase Auth handles the hard parts for you: it stores passwords hashed (scrambled one way, so even the database owner can't read them), issues and refreshes sessions, and sends confirmation emails. Never build your own password storage for a real app.
Setting up Supabase Auth in Next.js
Email and password sign-in is enabled by default in Supabase. In your Next.js app you need two more files, both based on Supabase's official Next.js starter.
1. Refresh sessions with proxy.ts
Sessions expire and must be refreshed. In Next.js 16, a file named proxy.ts in the project root runs before every matching request (older Next.js versions called this file middleware.ts). Supabase uses it to refresh the session cookie and, here, to send logged-out users to the login page:
// lib/supabase/proxy.ts
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({ request });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
);
},
},
},
);
// Don't run code between createServerClient and getClaims():
// getClaims() is what refreshes the session.
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
if (!user && request.nextUrl.pathname.startsWith("/students")) {
const url = request.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
// Return supabaseResponse as it is, so the refreshed cookies reach the browser.
return supabaseResponse;
}// proxy.ts
import { type NextRequest } from "next/server";
import { updateSession } from "@/lib/supabase/proxy";
export async function proxy(request: NextRequest) {
return await updateSession(request);
}
export const config = {
matcher: [
// Every path except static files and images.
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};2. Sign up, log in, and log out
The account actions are Server Actions, like the student forms in lesson 16. supabase.auth.signUp creates an account, signInWithPassword logs in (and sets the session cookies), and signOut ends the session:
// app/login/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
export type AuthState = { error?: string; message?: string; email?: string };
function readCredentials(formData: FormData) {
return {
email: String(formData.get("email") ?? "").trim().toLowerCase(),
password: String(formData.get("password") ?? ""),
};
}
export async function login(_state: AuthState, formData: FormData): Promise<AuthState> {
const { email, password } = readCredentials(formData);
if (!email || !password) {
return { error: "Enter your email and password.", email };
}
const supabase = await createClient();
const { error } = await supabase.auth.signInWithPassword({ email, password });
if (error) {
return { error: "That email and password don't match an account.", email };
}
revalidatePath("/", "layout");
redirect("/students");
}
export async function signup(_state: AuthState, formData: FormData): Promise<AuthState> {
const { email, password } = readCredentials(formData);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return { error: "Enter a valid email address.", email };
}
if (password.length < 8) {
return { error: "Use a password with at least 8 characters.", email };
}
const origin = (await headers()).get("origin");
const supabase = await createClient();
const { error } = await supabase.auth.signUp({
email,
password,
options: { emailRedirectTo: `${origin}/students` },
});
if (error) {
return { error: error.message, email };
}
return { message: "Check your email and click the link to confirm your account." };
}
export async function logout() {
const supabase = await createClient();
await supabase.auth.signOut();
revalidatePath("/", "layout");
redirect("/login");
}Notice the login error says "don't match an account" instead of "wrong password" or "no such email". Saying which one is wrong would tell an attacker which emails have accounts.
One form component serves both actions:
// app/login/AuthForm.tsx
"use client";
import { useActionState } from "react";
import type { AuthState } from "./actions";
type Props = {
action: (state: AuthState, formData: FormData) => Promise<AuthState>;
title: string;
submitLabel: string;
newPassword?: boolean;
};
export default function AuthForm({ action, title, submitLabel, newPassword = false }: Props) {
const [state, formAction, pending] = useActionState(action, {});
return (
<form action={formAction} className="grid gap-3 rounded-lg bg-white p-6 shadow">
<h2 className="text-lg font-bold">{title}</h2>
<label className="grid gap-1 text-sm font-medium">
Email
<input
name="email"
type="email"
autoComplete="email"
defaultValue={state.email}
required
className="h-11 rounded-lg border px-3"
/>
</label>
<label className="grid gap-1 text-sm font-medium">
Password
<input
name="password"
type="password"
autoComplete={newPassword ? "new-password" : "current-password"}
minLength={newPassword ? 8 : undefined}
required
className="h-11 rounded-lg border px-3"
/>
</label>
{state.error && (
<p role="alert" className="text-sm text-red-700">{state.error}</p>
)}
{state.message && (
<p role="status" className="text-sm text-emerald-700">{state.message}</p>
)}
<button
disabled={pending}
className="h-11 rounded-lg bg-violet-600 font-semibold text-white disabled:opacity-60"
>
{pending ? "Please wait..." : submitLabel}
</button>
</form>
);
}// app/login/page.tsx
import AuthForm from "./AuthForm";
import { login, signup } from "./actions";
export default function LoginPage() {
return (
<section className="grid gap-6 sm:grid-cols-2">
<AuthForm action={login} title="Log in" submitLabel="Log in" />
<AuthForm action={signup} title="Create an account" submitLabel="Create account" newPassword />
</section>
);
}autoComplete="current-password" and "new-password" let password managers fill in or suggest passwords.
3. Confirming email addresses
Hosted Supabase projects require users to confirm their email before they can log in. The confirmation link must come back to your app, which turns it into a session. Add this Route Handler from the official starter:
// app/auth/confirm/route.ts
import { type EmailOtpType } from "@supabase/supabase-js";
import { redirect } from "next/navigation";
import { type NextRequest } from "next/server";
import { createClient } from "@/lib/supabase/server";
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const token_hash = searchParams.get("token_hash");
const type = searchParams.get("type") as EmailOtpType | null;
const next = searchParams.get("next") ?? "/";
if (token_hash && type) {
const supabase = await createClient();
const { error } = await supabase.auth.verifyOtp({ type, token_hash });
if (!error) {
redirect(next);
}
}
redirect("/login");
}Then, in the Supabase dashboard:
-
On the Email Templates page, edit Confirm signup so its link points to that route:
<a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next={{ .RedirectTo }}">Confirm email address</a> -
On the URL Configuration page, keep Site URL as
http://localhost:3000while developing, and addhttp://localhost:3000/**to Redirect URLs. (Lesson 19 adds your live address.)
While building, you may instead switch off Confirm email for the Email provider (on the Auth Providers page). Users are then confirmed the moment they sign up, which saves time with test accounts, but anyone could register with an email they don't own. Turn it back on before real users arrive.
Protecting pages and actions
proxy.ts redirects logged-out visitors away from /students, but treat it as a convenience, not your only lock. Check the user again where the data is used: Server Actions can be called with a direct request, without your page, so every action must check who is calling.
On the server, check the user with supabase.auth.getClaims(), which verifies the session. Don't trust supabase.auth.getSession() in server code: it reads the cookie without verifying it, and cookies can be forged.
A helper keeps the check in one place:
// lib/auth.ts
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
export async function requireUser() {
const supabase = await createClient();
const { data, error } = await supabase.auth.getClaims();
if (error || !data?.claims) {
redirect("/login");
}
return { supabase, userId: data.claims.sub };
}Use it wherever lesson 16 called createClient() for student data. The data module:
// lib/students.ts
import { requireUser } from "@/lib/auth";
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 requireUser();
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 requireUser();
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;
}And the actions. Only the lines that get the Supabase client change, but here's the whole file so you can compare:
// app/students/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
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: "You already have a student with that number." } };
}
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 { supabase } = await requireUser();
const values = readForm(formData);
const result = validateStudent(values);
if (!result.ok) {
return { errors: result.errors, values };
}
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 { supabase } = await requireUser();
const values = readForm(formData);
const result = validateStudent(values);
if (!result.ok) {
return { errors: result.errors, values };
}
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 requireUser();
const { error } = await supabase.from("students").delete().eq("id", id);
if (error) {
throw new Error(`Could not delete student ${id}: ${error.message}`);
}
revalidatePath("/students");
}The code doesn't send a user_id and doesn't filter by user. The database does both, through the policies in the last section. That's deliberate: a rule enforced by the database can't be skipped by a forgotten line of code.
Finally, show who's logged in, with a logout button, in the navigation bar. The menu reads the session, so it sits in its own <Suspense>:
// app/components/UserMenu.tsx
import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { logout } from "@/app/login/actions";
export default async function UserMenu() {
const supabase = await createClient();
const { data } = await supabase.auth.getClaims();
if (!data?.claims) {
return <Link href="/login" className="ml-auto font-semibold">Log in</Link>;
}
return (
<div className="ml-auto flex items-center gap-3">
<span className="hidden text-sm text-gray-500 sm:inline">{data.claims.email}</span>
<form action={logout}>
<button className="text-sm font-semibold">Log out</button>
</form>
</div>
);
}// app/layout.tsx
import type { Metadata } from "next";
import Link from "next/link";
import { Suspense } from "react";
import UserMenu from "@/app/components/UserMenu";
import "./globals.css";
export const metadata: Metadata = {
title: "Class Portal",
description: "Subjects and students of BSCS 3A",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className="bg-gray-50 text-gray-900">
<nav className="flex items-center gap-4 border-b bg-white px-6 py-3">
<Link href="/" className="font-bold">Class Portal</Link>
<Link href="/students">Students</Link>
<Suspense fallback={null}>
<UserMenu />
</Suspense>
</nav>
<main className="mx-auto max-w-4xl p-6">{children}</main>
</body>
</html>
);
}Quick check
Validating and safely showing input
Never trust input. Anything from a form, a URL, a cookie, or an API request can be changed by the user. The rules:
- Validate on the server (like
validateStudentand the checks insignup): types, lengths, formats, allowed values. Browser validation is only for convenience. - Allow-list instead of block-list. Accept
BSCSorBSITonly, rather than trying to list every bad value. - Keep database constraints as the final check.
Two classic attacks and how this stack handles them:
| Attack | What happens | Your protection |
|---|---|---|
| SQL injection | input is pasted into an SQL string and changes the query (lesson 8) | supabase-js sends values separately from the query, like PDO's prepared statements. Never build SQL or filter strings by gluing raw input together. |
| Cross-site scripting (XSS) | a user saves <script>...</script> as their name, and it runs in other users' browsers | React escapes {text}, so it shows as plain text. Don't use dangerouslySetInnerHTML with user input, and don't put user input in href without checking it starts with https://. |
Exercise · JavaScript
Password rules
Complete checkPassword so it returns a list of problems: at least 8 characters if it's shorter than 8, a number if it has no digit, and a letter if it has no letter (in that order). The loop should print the four lines below.
Expected output
abc: needs at least 8 characters, a number password: needs a number 12345678: needs a letter bisu2026: OK
Hint
Use password.length < 8, !/[0-9]/.test(password), and !/[a-zA-Z]/.test(password), pushing a message for each.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
function checkPassword(password) {
const problems = [];
if (password.length < 8) problems.push("at least 8 characters");
if (!/[0-9]/.test(password)) problems.push("a number");
if (!/[a-zA-Z]/.test(password)) problems.push("a letter");
return problems;
}
for (const pw of ["abc", "password", "12345678", "bisu2026"]) {
const problems = checkPassword(pw);
console.log(pw + ": " + (problems.length ? "needs " + problems.join(", ") : "OK"));
}
Environment variables and secrets
Configuration that changes between computers, or must stay private, goes in environment variables, not in code. In Next.js:
- Variables in
.env.localare available on the server asprocess.env.NAME. - Only variables whose names start with
NEXT_PUBLIC_reach the browser. Next.js copies their values into the JavaScript it sends to users when you build, so treat everyNEXT_PUBLIC_value as public. - The default
.gitignorefromcreate-next-appexcludes.envfiles. Keep it that way, and commit a.env.examplewith the variable names and fake values so teammates know what to set:
# .env.example (copy to .env.local and fill in real values)
NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_your_key_hereFor Supabase specifically:
| Key | Where it may be used |
|---|---|
publishable key (NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY) | browser and server; safe to expose because RLS limits what it can do |
secret key (sb_secret_...) | server only, and only when you truly need to bypass RLS (for example, an admin task). Never name it NEXT_PUBLIC_..., never import it in a client component, never commit it. |
If a secret is ever committed or shared, rotate it: create a new key in the dashboard and delete the old one. Removing it from your code isn't enough, because it stays in Git history.
To make sure server-only code never ends up in the browser, add import "server-only"; (from the server-only package) at the top of a module that uses secrets. If a client component imports it by mistake, the build fails instead of leaking the secret.
Quick check
Securing database access with RLS
Lesson 16's "Practice" policies let anyone change anything. Now replace them so that each user owns the rows they create. Run this in the SQL Editor:
-- 1. Remove the practice rows (they belong to no one) and the open policies.
delete from public.students;
drop policy "Practice: anyone can read students" on public.students;
drop policy "Practice: anyone can add students" on public.students;
drop policy "Practice: anyone can edit students" on public.students;
drop policy "Practice: anyone can delete students" on public.students;
-- 2. Every row now belongs to the user who created it.
alter table public.students
add column user_id uuid not null default auth.uid()
references auth.users (id) on delete cascade;
create index on public.students (user_id);
-- A student number only has to be unique within one user's records.
alter table public.students drop constraint students_student_no_key;
alter table public.students add unique (user_id, student_no);
-- 3. Only logged-in users reach the table at all.
revoke all on table public.students from anon;
-- 4. Each user sees and changes only their own rows.
create policy "Users can view their own students"
on public.students for select to authenticated
using ( (select auth.uid()) = user_id );
create policy "Users can add their own students"
on public.students for insert to authenticated
with check ( (select auth.uid()) = user_id );
create policy "Users can edit their own students"
on public.students for update to authenticated
using ( (select auth.uid()) = user_id )
with check ( (select auth.uid()) = user_id );
create policy "Users can delete their own students"
on public.students for delete to authenticated
using ( (select auth.uid()) = user_id );How it works:
auth.uid()returns the ID of the logged-in user making the request. As the column's default, it fills inuser_idautomatically on insert.using (...)filters which existing rows a user can see, update, or delete. Rows that don't match simply aren't there for them: another user's update or delete affects 0 rows.with check (...)tests new or changed rows. Inserting a row with someone else'suser_id, or changing a row'suser_idto someone else, fails with "new row violates row-level security policy".- Writing
(select auth.uid())instead ofauth.uid()lets PostgreSQL compute it once per query instead of once per row, which Supabase recommends for speed, along with the index onuser_id. revoke ... from anonmeans logged-out requests get "permission denied" even before RLS.
Test it like an attacker: create two accounts, add students with each, and confirm neither can see or change the other's.
Quick check
Common mistakes
- Protecting pages but not Server Actions or Route Handlers.
- Trusting
getSession()on the server; usegetClaims(). - Showing different errors for "no such email" and "wrong password".
- Putting a secret in a
NEXT_PUBLIC_variable, or committing.env.local. - Leaving practice policies (
using ( true )for writes) in a real app. - Forgetting
with checkon insert and update policies, which lets users create rows for someone else. - Rendering user input as HTML with
dangerouslySetInnerHTML.
Summary
- Authentication proves who you are; authorization decides what you may do. Sessions live in cookies.
- Supabase Auth:
signUp,signInWithPassword,signOut;proxy.tsrefreshes sessions;/auth/confirmcompletes email confirmation; set the Site URL and Redirect URLs. - Check the user with
getClaims()in every place that reads or changes data, including every Server Action. - Validate input on the server with allow-lists; React escapes output; supabase-js keeps values out of the SQL text.
- Only
NEXT_PUBLIC_variables reach the browser. Keep secret keys on the server and out of Git, and rotate any that leak. - RLS with
auth.uid()makes the database enforce ownership:usingfor reading and changing,with checkfor new data.
Next: testing and debugging, including how to use AI tools without letting them put bugs and security holes in your app.