Series Kubernetes & Helm from scratch · Part 5
Building the Next.js frontend
Build the Next.js 15 frontend for our auth app: App Router, Server Actions, Zod validation, a typed API client and HttpOnly cookie sessions.
In part 4 we built a Spring Boot API that registers users, checks passwords, sends a one-time MFA code and returns a JWT. An API on its own isn’t something a person can use, so in this part we build the frontend in apps/frontend: a Next.js 15 app with four screens (register, log in, enter the code, dashboard).
One decision shapes the whole design: the browser never talks to the backend. Every call to the Spring Boot API is made by the Next.js server, and the JWT lives in an HttpOnly cookie that JavaScript in the page can’t read. That keeps the token away from cross-site scripting, means the backend needs no CORS configuration, and it maps neatly onto Kubernetes later. In part 10 the frontend pod will reach the backend through a cluster-internal Service name, and the backend never needs to be exposed to the internet at all.
Who talks to whom
This pattern is usually called a backend-for-frontend. Server Actions make it cheap to build: a form posts straight to a server function, and that function can read and write cookies and call internal services.
Create the project
From the repository root:
cd apps
npx create-next-app@15 frontend --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
cd frontend
npm install zod server-only
The flags answer the setup questions up front: TypeScript, Tailwind, ESLint, the App Router, a src/ directory and the @/ import alias. zod validates form input. server-only is a tiny package that makes the build fail if a module marked with it is ever imported into client code, which is how we stop the API client (and the backend URL) leaking into the browser bundle.
Create apps/frontend/.env.local for local development:
BACKEND_URL=http://localhost:8080
The variable has no NEXT_PUBLIC_ prefix on purpose. Next.js only inlines NEXT_PUBLIC_* variables into browser code; anything else is read on the server at runtime. That matters for Kubernetes: one image can point at a different backend in each environment just by changing an environment variable, with no rebuild.
The layout we’re aiming for:
src/
lib/
api.ts typed client for the Spring Boot API (server only)
session.ts read/write the HttpOnly cookies
schemas.ts Zod schemas shared by the actions
app/
actions.ts register, login, verify, logout Server Actions
register/page.tsx login/page.tsx mfa/page.tsx dashboard/page.tsx
components/
AuthForm.tsx client component that shows pending state and errors
middleware.ts redirects anonymous users away from /dashboard
A typed API client
All knowledge of the backend’s URLs and JSON shapes lives in one file. The rest of the app calls functions, not endpoints.
src/lib/api.ts:
import "server-only";
const BASE = process.env.BACKEND_URL ?? "http://localhost:8080";
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
...init,
headers: { "Content-Type": "application/json", ...init.headers },
cache: "no-store", // auth responses must never be cached
});
if (!res.ok) throw new ApiError(res.status, `${path} returned ${res.status}`);
const text = await res.text();
return (text ? JSON.parse(text) : undefined) as T;
}
export type Me = { id: string; email: string };
export const api = {
register: (email: string, password: string) =>
call<void>("/api/auth/register", { method: "POST", body: JSON.stringify({ email, password }) }),
login: (email: string, password: string) =>
call<void>("/api/auth/login", { method: "POST", body: JSON.stringify({ email, password }) }),
verifyMfa: (email: string, code: string) =>
call<{ token: string }>("/api/auth/mfa/verify", { method: "POST", body: JSON.stringify({ email, code }) }),
me: (token: string) =>
call<Me>("/api/me", { headers: { Authorization: `Bearer ${token}` } }),
};
Points worth noting:
import "server-only"is the first line, so a client component that imports this file breaks the build instead of silently shipping it.registerandloginreturn201and202with no body, hence the empty-text check beforeJSON.parse.- Every non-2xx response becomes an
ApiErrorcarrying the status code, so callers can tell401(bad credentials or code) from409(email taken) from a5xx.
Sessions in HttpOnly cookies
src/lib/session.ts:
import "server-only";
import { cookies } from "next/headers";
const SESSION = "session";
const PENDING = "mfa_email";
const base = {
httpOnly: true, // invisible to document.cookie
secure: process.env.NODE_ENV === "production", // HTTPS only outside dev
sameSite: "lax" as const, // not sent on cross-site POSTs
path: "/",
};
export async function setSession(token: string) {
(await cookies()).set(SESSION, token, { ...base, maxAge: 15 * 60 }); // matches JWT expiry
}
export async function getSession() {
return (await cookies()).get(SESSION)?.value;
}
export async function setPendingEmail(email: string) {
(await cookies()).set(PENDING, email, { ...base, maxAge: 5 * 60 }); // matches MFA code TTL
}
export async function getPendingEmail() {
return (await cookies()).get(PENDING)?.value;
}
export async function clearAll() {
const jar = await cookies();
jar.delete(SESSION);
jar.delete(PENDING);
}
In Next.js 15 cookies() is asynchronous, so it’s always awaited. The two lifetimes mirror the backend: the session cookie lasts as long as the 15-minute JWT, and the pending-email cookie, which remembers who is halfway through logging in, lasts as long as the five-minute MFA code in Redis. When either runs out on the backend, the cookie disappears at the same moment.
Validation with Zod
src/lib/schemas.ts:
import { z } from "zod";
export const credentials = z.object({
email: z.string().trim().email("Enter a valid email address"),
password: z.string().min(12, "Use at least 12 characters"),
});
export const mfaCode = z.object({
code: z.string().regex(/^\d{6}$/, "The code is six digits"),
});
Validation runs on the server inside each action. Browser-side checks such as required and type="email" are a convenience for the user; the Zod check is the one we rely on, because anyone can post to a Server Action without our form.
The Server Actions
- Register Validate, call
/api/auth/register, then redirect to/login. - Log in Validate, call
/api/auth/login, store the email in the short-livedmfa_emailcookie, redirect to/mfa. - Verify Read the email from the cookie, call
/api/auth/mfa/verify, put the JWT in thesessioncookie, redirect to/dashboard. - Dashboard A Server Component reads the cookie and calls
/api/mewith the token as a Bearer header.
src/app/actions.ts:
"use server";
import { redirect } from "next/navigation";
import { api, ApiError } from "@/lib/api";
import { credentials, mfaCode } from "@/lib/schemas";
import { clearAll, getPendingEmail, setPendingEmail, setSession } from "@/lib/session";
export type FormState = { error?: string };
export async function registerAction(_: FormState, form: FormData): Promise<FormState> {
const parsed = credentials.safeParse(Object.fromEntries(form));
if (!parsed.success) return { error: parsed.error.issues[0].message };
try {
await api.register(parsed.data.email, parsed.data.password);
} catch (e) {
if (e instanceof ApiError && e.status === 409) return { error: "That email is already registered" };
return { error: "Something went wrong, please try again" };
}
redirect("/login");
}
export async function loginAction(_: FormState, form: FormData): Promise<FormState> {
const parsed = credentials.safeParse(Object.fromEntries(form));
if (!parsed.success) return { error: parsed.error.issues[0].message };
try {
await api.login(parsed.data.email, parsed.data.password);
} catch {
return { error: "Email or password is incorrect" };
}
await setPendingEmail(parsed.data.email);
redirect("/mfa");
}
export async function verifyAction(_: FormState, form: FormData): Promise<FormState> {
const email = await getPendingEmail();
if (!email) redirect("/login"); // code expired or never requested
const parsed = mfaCode.safeParse(Object.fromEntries(form));
if (!parsed.success) return { error: parsed.error.issues[0].message };
try {
const { token } = await api.verifyMfa(email, parsed.data.code);
await setSession(token);
} catch {
return { error: "That code is wrong or has expired. Log in again for a new one." };
}
redirect("/dashboard");
}
export async function logoutAction() {
await clearAll();
redirect("/login");
}
Two details catch people out. First, redirect() works by throwing a special error, so it must sit outside the try block; inside, our catch would swallow it. Second, the login error message is the same whether the email is unknown or the password is wrong, matching the backend’s deliberate refusal to reveal which emails exist.
Gotcha: a wrong code burns it, because the backend's GETDEL deletes the code on any attempt. That's why the verify error tells the user to log in again rather than simply retry.
One form component for all three screens
Forms need a little client-side behaviour: showing the error the action returned and disabling the button while the request is in flight. React 19’s useActionState gives us both.
src/components/AuthForm.tsx:
"use client";
import { useActionState } from "react";
import type { FormState } from "@/app/actions";
type Field = { name: string; label: string; type: string; autoComplete?: string };
export function AuthForm({ action, fields, submit }: {
action: (state: FormState, form: FormData) => Promise<FormState>;
fields: Field[];
submit: string;
}) {
const [state, formAction, pending] = useActionState(action, {});
return (
<form action={formAction} className="mx-auto mt-16 flex max-w-sm flex-col gap-4">
{fields.map((f) => (
<label key={f.name} className="flex flex-col gap-1 text-sm">
{f.label}
<input name={f.name} type={f.type} autoComplete={f.autoComplete} required
className="rounded border px-3 py-2" />
</label>
))}
{state.error && <p role="alert" className="text-sm text-red-600">{state.error}</p>}
<button disabled={pending} className="rounded bg-black px-3 py-2 text-white disabled:opacity-50">
{pending ? "Please wait…" : submit}
</button>
</form>
);
}
Because the form uses action={formAction}, it still submits as a normal HTML form if JavaScript hasn’t loaded yet. Each page is then a few lines. src/app/mfa/page.tsx:
import { AuthForm } from "@/components/AuthForm";
import { verifyAction } from "@/app/actions";
export default function MfaPage() {
return (
<AuthForm
action={verifyAction}
submit="Verify"
fields={[{ name: "code", label: "Six-digit code", type: "text", autoComplete: "one-time-code" }]}
/>
);
}
The register and login pages are the same with email and password fields (autoComplete set to email and new-password or current-password, so password managers behave).
The protected dashboard
The dashboard is a Server Component, so it can await data directly:
import { redirect } from "next/navigation";
import { api } from "@/lib/api";
import { getSession } from "@/lib/session";
import { logoutAction } from "@/app/actions";
export default async function Dashboard() {
const token = await getSession();
if (!token) redirect("/login");
const me = await api.me(token).catch(() => null);
if (!me) redirect("/login"); // token expired or rejected
return (
<main className="mx-auto mt-16 max-w-sm">
<h1 className="text-xl font-semibold">Signed in as {me.email}</h1>
<form action={logoutAction}><button className="mt-4 underline">Log out</button></form>
</main>
);
}
The backend’s /api/me is the real authority: it checks the JWT’s signature and expiry. As a cheap first line, src/middleware.ts turns away requests that have no cookie at all before any rendering happens:
import { NextResponse, type NextRequest } from "next/server";
export function middleware(req: NextRequest) {
if (!req.cookies.has("session")) return NextResponse.redirect(new URL("/login", req.url));
}
export const config = { matcher: ["/dashboard/:path*"] };
Test the whole flow locally
Start PostgreSQL, Redis and the backend as in part 4, then in a second terminal:
cd apps/frontend
npm run dev
Open http://localhost:3000/register and walk through it:
/login./mfa; the backend log prints the six-digit code.session is marked HttpOnly, and document.cookie in the console doesn't show it./dashboard: you're redirected to /login.Finally, check that a production build works, because that’s what the container will run in the next part:
npm run build && npm start
Takeaways
- The browser only talks to Next.js; Next.js talks to Spring Boot server to server, so the backend needs no CORS and no public exposure.
- The JWT lives in an
HttpOnly,SameSite=Laxcookie whose lifetime matches the token; page scripts can’t read it. - A single
server-onlyAPI client owns every backend URL and JSON shape, and fails the build if imported client-side. - Zod validates every Server Action on the server; browser checks are only a convenience.
- Keep
redirect()outsidetry/catch, and awaitcookies()in Next.js 15. BACKEND_URLwithout aNEXT_PUBLIC_prefix is read at runtime, so one image can serve every environment.
Next, in part 6, we containerise both apps with multi-stage Dockerfiles and run them in Minikube as plain manifests.