Frontend
Admin page
Add a Next.js admin page that uploads notes and follows every section live, proxy the API through Next.js, and lock it with one password.
By the end of this page you open http://localhost:3000, log in, upload an intake, and watch the sections change from Waiting to Writing to Done without a reload.
The browser talks only to Next.js. A rewrite sends /api/* on to FastAPI, so there is one origin and no CORS to set up. HTTP Basic auth in src/proxy.ts is the smallest honest lock for one admin. The signing pages you add later stay public.
Send the API calls to FastAPI
import type { NextConfig } from "next";
// Local runs read the project .env, like the backend. In Docker, Compose sets the variables.
try { process.loadEnvFile("../.env"); } catch {}
const config: NextConfig = {
// The browser talks only to Next.js. Other /api calls go on to FastAPI.
rewrites: async () => [
{ source: "/api/:path*", destination: `${process.env.API_URL || "http://localhost:8000"}/api/:path*` },
],
};
export default config;process.loadEnvFile reads the same .env as the backend, so ADMIN_PASSWORD and API_URL work locally. In Docker it finds no file and Compose sets the variables instead.
Lock the admin page
import { NextResponse, type NextRequest } from "next/server";
// One password for the admin page and its API. The signing pages stay public.
export function proxy(request: NextRequest) {
const password = process.env.ADMIN_PASSWORD;
if (password && request.headers.get("authorization") === `Basic ${btoa(`admin:${password}`)}`)
return NextResponse.next();
return new NextResponse("Login required", { status: 401, headers: { "WWW-Authenticate": 'Basic realm="admin"' } });
}
export const config = { matcher: ["/", "/api/contracts/:path*"] };The matcher covers the admin page and the admin API. The browser shows its own login box when it gets the WWW-Authenticate header. The user is always admin. Without ADMIN_PASSWORD in .env, every request gets a 401.
proxy.ts, not middleware.ts
Next.js 16 renamed middleware.ts to proxy.ts, and the exported function to proxy. Older examples online still use the old names.
Add the layout
Create the folder frontend/src/app.
export const metadata = { title: "Contract signing", robots: { index: false, follow: false } };
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<link rel="stylesheet" href="/sign.css" />
<link rel="preload" href="/fonts/Allura-Regular.ttf" as="font" type="font/ttf" crossOrigin="anonymous" />
</head>
<body>{children}</body>
</html>
);
}The stylesheet and the fonts come with the starter, in frontend/public/. The class names in the pages below all come from sign.css.
Write the admin page
"use client";
import { useEffect, useState } from "react";
type Row = { id: number; title: string; status: string; contract_type: string | null };
type Contract = Row & { reason: string | null; token: string | null; sections: { title: string; status: string; text: string }[] };
const LABELS: Record<string, string> = { pending: "Waiting", needs_review: "Needs review" };
const label = (status: string) => LABELS[status] || status[0].toUpperCase() + status.slice(1);
async function api(path = "", method = "GET", body?: object) {
const response = await fetch(`/api/contracts${path}`, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
return response.json();
}
export default function Admin() {
const [rows, setRows] = useState<Row[]>([]);
const [open, setOpen] = useState<Contract | null>(null);
const [notes, setNotes] = useState("");
const busy = rows.some((row) => ["pending", "processing"].includes(row.status));
async function load(id = open?.id) {
setRows(await api());
if (id) setOpen(await api(`/${id}`));
}
useEffect(() => { load(); }, []);
useEffect(() => {
if (!busy) return;
const timer = setInterval(load, 2000); // Refetch while something is processing.
return () => clearInterval(timer);
}, [busy, open?.id]);
async function upload() {
const { id } = await api("", "POST", { notes });
setNotes("");
load(id);
}
const action = async (name: string) => { await api(`/${open!.id}/${name}`, "POST"); load(); };
return (
<div className="sign-app">
<header className="sign-topbar">
<div className="sign-topbar-title"><span>Contracts</span><span className="sign-document-name">Upload intake notes, review the draft, send it for signing</span></div>
</header>
<div className="admin">
<aside>
<section className="sign-paper">
<h2>New contract</h2>
<textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Paste the intake meeting notes" />
<input type="file" accept=".md,.txt" onChange={async (e) => setNotes(await e.target.files![0].text())} />
<button className="sign-button" disabled={notes.trim().length < 20} onClick={upload}>Process</button>
</section>
{rows.map((row) => (
<button key={row.id} className="admin-row" onClick={() => load(row.id)}>
<span>{row.title}</span><span className="local-label">{label(row.status)}</span>
</button>
))}
</aside>
{open && (
<main className="sign-paper">
<div className="paper-section-heading"><h2>{open.title}</h2><span className="local-label">{label(open.status)}</span></div>
{open.reason && <div className="sign-alert">{open.reason}</div>}
{open.status === "failed" && <button className="sign-button secondary" onClick={() => action("retry")}>Retry</button>}
{open.status === "drafted" && <button className="sign-button" onClick={() => action("send")}>Send</button>}
{open.token && <p>Signing link: <input readOnly value={`${location.origin}/sign/${open.token}`} onFocus={(e) => e.target.select()} /></p>}
{open.sections.map((section) => (
<section key={section.title} className="contract-section">
<h2>{section.title} <span className="local-label">{label(section.status)}</span></h2>
<p>{section.text}</p>
</section>
))}
</main>
)}
</div>
</div>
);
}The page has one list and one open contract. While any contract is pending or processing, it fetches the list and the open contract every two seconds, and it stops when nothing is running. Picking a file puts its text in the box, so you can still edit the notes before you click Process.
The Retry and Send buttons are already there. Send works once the backend has the route, two pages from now.
Check
Keep the API running, and start the frontend in a second terminal:
cd frontend
pnpm devOpen http://localhost:3000. The browser asks for a login. Use admin and your ADMIN_PASSWORD. Pick samples/intakes/01-dental-phone-receptionist.md, click Process, and watch the section labels change from Waiting to Writing to Done.
Then check the lock from a third terminal:
curl -i http://localhost:3000/api/contracts
# HTTP/1.1 401 UnauthorizedStop pnpm dev and run the type check and a production build:
pnpm typecheck && pnpm buildBoth pass. next dev writes a frontend/AGENTS.md for coding agents. It is already in .gitignore. Start pnpm dev again before you go on.
Background processing
Run the pipeline with FastAPI BackgroundTasks after the upload returns, save the status of every step, and retry from the first unfinished section.
Gmail SMTP
Create a Gmail account for the demo, turn on 2-Step Verification, make an app password, and send email from FastAPI over SMTP.