Was macht next-safe-action?
Übersicht
next-safe-action fügt Typsicherheit, Eingabevalidierung und Middleware zu Next.js Server Actions hinzu. Statt FormData manuell zu parsen und Fehler zu behandeln, definieren Sie ein Zod-Schema und erhalten validierte, typisierte Eingaben mit automatischer Fehlerbehandlung.
Anleitung
Schritt 1: Einrichtung
npm install next-safe-action zod
// lib/safe-action.ts — Action-Client mit Auth-Middleware
import { createSafeActionClient } from 'next-safe-action'
import { auth } from '@/auth'
// Öffentliche Aktionen (keine Authentifizierung erforderlich)
export const publicAction = createSafeActionClient()
// Authentifizierte Aktionen
export const authAction = createSafeActionClient({
async middleware() {
const session = await auth()
if (!session?.user) throw new Error('Nicht authentifiziert')
return { user: session.user }
},
})
Schritt 2: Aktionen definieren
// actions/projects.ts — Typsichere Server Actions
'use server'
import { authAction } from '@/lib/safe-action'
import { z } from 'zod'
import { prisma } from '@/lib/db'
import { revalidatePath } from 'next/cache'
const createProjectSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
})
export const createProject = authAction
.schema(createProjectSchema)
.action(async ({ parsedInput, ctx }) => {
const project = await prisma.project.create({
data: {
...parsedInput,
ownerId: ctx.user.id,
},
})
revalidatePath('/dashboard')
return { project }
})
const updateProjectSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1).max(100).optional(),
description: z.string().max(500).optional(),
status: z.enum(['active', 'archived']).optional(),
})
export const updateProject = authAction
.schema(updateProjectSchema)
.action(async ({ parsedInput, ctx }) => {
const { id, ...data } = parsedInput
// Besitz überprüfen
const project = await prisma.project.findFirst({
where: { id, ownerId: ctx.user.id },
})
if (!project) throw new Error('Projekt nicht gefunden')
const updated = await prisma.project.update({
where: { id },
data,
})
revalidatePath(`/projects/${id}`)
return { project: updated }
})
Schritt 3: In Komponenten verwenden
// components/CreateProjectForm.tsx — Formular mit sicherer Aktion
'use client'
import { useAction } from 'next-safe-action/hooks'
import { createProject } from '@/actions/projects'
export function CreateProjectForm() {
const { execute, result, isExecuting } = useAction(createProject)
return (
<form action={execute}>
<input name="name" placeholder="Projektname" required />
<textarea name="description" placeholder="Beschreibung (optional)" />
{result.validationErrors && (
<div className="errors">
{Object.entries(result.validationErrors).map(([field, errors]) => (
<p key={field}>{field}: {errors?.join(', ')}</p>
))}
</div>
)}
{result.serverError && (
<p className="error">{result.serverError}</p>
)}
<button disabled={isExecuting}>
{isExecuting ? 'Erstelle...' : 'Projekt erstellen'}
</button>
</form>
)
}
Richtlinien
- Verwenden Sie immer Zod-Schemata für die Eingabevalidierung – vertrauen Sie niemals clientseitig übermittelten Daten.
- Nutzen Sie Middleware für die Authentifizierung – sie wird vor jeder Aktion in der Kette ausgeführt.
- Der
useAction-Hook bietetisExecuting,resultund automatische Fehlerbehandlung. - Kombinieren Sie mit
useOptimisticActionfür sofortiges UI-Feedback. - Revalidieren Sie Pfade/Tags nach Mutationen, um die UI mit der Datenbank synchron zu halten.