AI Governance in Next.js: Where Should the Checks Actually Run?
A browser masks an email address before sending a prompt. Where is the decision to allow that request actually made?

A browser masks an email address before sending a prompt. Where is the decision to allow that request actually made?
The preview is useful feedback, but the server still has to decide whether this person may send this data to this model. We'll follow that request through the browser, a server policy check, and output validation, then separate provenance and audit delivery from the promises a UI badge might imply.
Client checks are advisory
A browser can help people notice sensitive input and understand AI output. It cannot be the sole authority for access control, data-loss prevention, or legal compliance: users can bypass client code. These examples show individual controls, not an installed governance platform.
This dependency-free helper previews two recognizable patterns. It neither detects every secret nor blocks prompt injection. Findings are not a safety verdict, and absence of findings is not clearance to transmit.
export function previewPrompt(raw: string) {
if (raw.length > 8000) throw new RangeError("Prompt exceeds this example's limit.");
const findings = new Set<string>();
const preview = raw
.replace(/\bBearer[ \t]+[A-Za-z0-9._~+\/-]+=*/gi, () => {
findings.add("bearer-token-pattern");
return "Bearer [REDACTED]";
})
.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, () => {
findings.add("email-pattern");
return "[REDACTED_EMAIL]";
});
return { preview, findings: [...findings] };
}Keep the original prompt out of analytics. Show the preview for user review, and independently enforce policy at the trusted boundary. Pattern matches can be false positives; redaction does not itself anonymize data.
Enforce policy before calling a model
In an example Next.js project, install Zod and server-only. Put this in governed-answer.ts, a server-only module called by an authenticated route or action. TrustedServices must be constructed on the server: its authorization and prompt-policy functions must genuinely enforce your rules, not accept a client-supplied “approved” flag.
import "server-only";
import { z } from "zod";
const requestSchema = z.strictObject({
prompt: z.string().trim().min(1).max(8000),
});
export const answerSchema = z.strictObject({
summary: z.string().min(1).max(2000),
limitations: z.array(z.string().min(1).max(200)).max(8),
});
export type GovernedAnswer = z.infer<typeof answerSchema>;
interface TrustedServices {
requirePermission(permission: "ai:generate"): Promise<void>;
enforcePromptPolicy(prompt: string): Promise<void>;
generate(prompt: string, signal: AbortSignal): Promise<unknown>;
}
export async function createGovernedAnswer(
raw: unknown,
services: TrustedServices,
signal: AbortSignal,
): Promise<GovernedAnswer> {
signal.throwIfAborted();
await services.requirePermission("ai:generate");
const { prompt } = requestSchema.parse(raw);
await services.enforcePromptPolicy(prompt);
signal.throwIfAborted();
const candidate = await services.generate(prompt, signal);
signal.throwIfAborted();
return answerSchema.parse(candidate);
}Read the function in order: permission first, input and prompt policy next, generation after those checks, then validation of the complete answer. A browser's reassuring preview never substitutes for any of these steps. Each boundary has a concrete place in the request path.
Authentication, tenant scope, rate limits, origin/CSRF protections where applicable, and provider permissions belong at that boundary. Errors propagate; the route must map and record them without exposing prompt content. The limits here are example policy caps, not performance measurements.
Validate a complete parsed result, not arbitrary streaming text chunks. Partial output can be displayed as provisional text, but must not authorize tools or transactions before final validation. A valid schema constrains shape, not factual accuracy or intent.
import type { GovernedAnswer } from "./governed-answer";
export function AnswerCard({ answer }: { answer: GovernedAnswer }) {
return (
<section aria-label="AI-generated draft">
<p>AI-generated draft. Check important claims before use.</p>
<p>{answer.summary}</p>
<ul>
{answer.limitations.map((text, index) => <li key={index}>{text}</li>)}
</ul>
</section>
);
}Save this as AnswerCard.tsx. React text interpolation escapes the content; it is not raw HTML or an automatically verified provenance badge. If a feature needs Markdown or HTML, use context-appropriate sanitization and URL policies instead of treating model output as trusted markup.
Article 50 is not a universal C2PA mandate
Article 113 gives the Act's general application date as 2 August 2026; assess applicable exceptions and transitional rules. Article 50 distinguishes providers' interaction disclosures and machine-readable marking duties from deployers' duties for deepfakes and certain public-interest text. Scope, exceptions, technical feasibility, and accessibility matter. The Article does not prescribe C2PA for every web application.
The following separate PNG example uses @contentauth/c2pa-node 0.10.0, which requires Node.js 22 or later. Run it in a Node server environment, not Edge or a browser. Supply a protected, correctly configured LocalSigner; never send signing keys to the client. The helper is private server code, not an exposed signing endpoint.
import "server-only";
import {
Builder,
type DestinationBufferAsset,
type LocalSigner,
} from "@contentauth/c2pa-node";
export async function signGeneratedPng(
png: Buffer,
signer: LocalSigner,
): Promise<Buffer> {
const builder = await Builder.newAsync();
builder.setIntent({
create: "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
});
const output: DestinationBufferAsset = { buffer: null };
builder.sign(signer, { buffer: png, mimeType: "image/png" }, output);
if (!output.buffer) throw new Error("Signing produced no output asset.");
return output.buffer;
}Use create intent only for a newly generated asset; editing existing media requires appropriate ingredients and edit history. The caller must enforce media-size and format policy. Validate the returned asset with a Reader and assess certificate trust, signature integrity, and assertions separately. A locally generated test certificate is not a publicly trusted credential.
C2PA records signed claims about provenance, not proof that content is true or legally compliant. A custom “compliant” assertion or green badge cannot establish either. Plain text in a React card is not automatically a signed media asset.
Audit delivery is not immutability
A prompt hash may remain identifiable through guessing or correlation; hashing is not automatic anonymization. Minimize event fields, control access and retention, and avoid raw prompts, credentials, or unnecessary identifiers. OpenTelemetry is instrumentation, not an immutable ledger.
A fetch promise does not prove durable ingestion: check HTTP status and the collector's acknowledgement contract. For durable audit requirements, use authenticated server-side collection, idempotency, bounded retries or an outbox, and explicit failure handling. Define whether failure blocks an operation or leaves it visibly pending. Measure actual workload and bundle costs instead of publishing unsupported millisecond or size estimates. This is engineering guidance, not a legal compliance determination.
For each control, ask which component owns the decision and what happens if that component fails. A helpful preview, an enforced policy, a signed claim, and a durable audit record solve different problems. The interface should make those differences understandable rather than collapsing them into one green badge.