The expected type of the input for the server action.
The expected return type of the server action.
A wrapped server action function that can be used directly in Next.js.
// app/actions.ts (Server Component)
"use server";
import { createServerAction } from "../../src/integrations/server-actions";
import { contract } from "../../src/core/contract";
import { auth } from "../../src/conditions/auth";
import { z } from "zod";
import { validates } from "../../src/conditions/validation";
const CreatePostSchema = z.object({
title: z.string().min(1),
content: z.string().min(10),
});
class PostActions {
@contract({
requires: [auth("user"), validates(CreatePostSchema)],
})
async createPost(input: z.infer<typeof CreatePostSchema>, context: any) {
console.log("Creating post:", input, "by user:", context.user?.id);
// Logic to save post to DB
return { postId: "new-post-id", ...input };
}
}
export const createPostAction = createServerAction(new PostActions().createPost);
Helper to integrate Next.js Server Actions with the contract system. This function acts as a wrapper for Server Actions, handling contract violations appropriately. It extracts input from FormData (if applicable), retrieves the authentication context, executes the action, and catches
ContractViolationError
to return a structured response or redirect.