Execute asynchronous server logic directly from your components with seamless Flight RPC. Dinou uniquely allows Server Functions to return live, rendered React components as well as serializable data, with native React 19 form actions and hooks.
Server Functions (also known as Server Actions in the React Server Components ecosystem) are asynchronous JavaScript/TypeScript functions that run exclusively in the server runtime. They establish a type-safe, seamless Remote Procedure Call (RPC) bridge between client and server.
In Dinou, you can author Server Functions using two standard modalities:
"use server" at the very top of a dedicated action file."use server" inside individual function bodies—including top-level functions in mixed utility files and inline closures inside Server Components.fetch() boilerplate, or JSON serializing required. Dinou generates typed RPC endpoints automatically.Dinou provides native compiler support for both declaration modalities across esbuild, Rollup, and Webpack:
Placed at the very first line of a file. Every exported function (named or export default) automatically becomes a public Server Function reference.
import { updateUser } from "@/actions/users".src/actions/auth.ts, src/actions/billing.ts).Placed as the first statement inside a function body in a mixed file or Server Component.
"use server" are automatically exported by Dinou's AST compiler..bind()), while module-scope bindings stay strictly on the server.// src/actions/users.ts
"use server"; // 👈 Line 1: entire module is dedicated to Server Functions
import { db } from "@/server/db";
// Exported: registered in manifest and callable from client
export async function updateUserEmail(userId: string, email: string) {
await db.users.update(userId, { email });
return { success: true };
}
// Exported: also registered in manifest
export async function deleteUserAccount(userId: string) {
await db.users.delete(userId);
return { success: true };
}
// Unexported: strictly private helper, NEVER exposed over HTTP
function hashKey(key: string) {
return crypto.createHash("sha256").update(key).digest("hex");
}// src/utils/billing.ts
// Note: NO "use server" at module top!
import { db } from "@/server/db";
// Normal server helper: NEVER in manifest, cannot be called via HTTP
export function calculateTax(amount: number) {
return amount * 0.21;
}
// Explicit Server Function: callable remotely via RPC
export async function submitPayment(cartId: string, amount: number) {
"use server"; // 👈 Function body directive
return await db.charges.create({ cartId, amount });
}
// Unexported action: auto-exported by Dinou AST compiler for dynamic ESM dispatch
async function internalAuditLog(event: string) {
"use server";
return await db.audit.insert({ event });
}// src/profile/[userId]/page.tsx (Server Component)
import type { PageProps } from "./dinou";
import { getContext } from "dinou/server";
import { db } from "@/server/db";
import { ProfileForm } from "./profile-form"; // Client Component
export default async function ProfilePage({ params }: PageProps) {
const user = await db.users.find(params.userId);
// Inline Server Function capturing public `params.userId` via closure
async function updateBio(formData: FormData) {
"use server";
// Always read secrets & verify session auth INSIDE the server function body:
const ctx = getContext();
const sessionUser = await verifySession(ctx.req.cookies.session_token);
if (!sessionUser || sessionUser.id !== params.userId) {
throw new Error("Unauthorized");
}
const bio = formData.get("bio") as string;
await db.users.update(params.userId, { bio });
return { ok: true };
}
// Passed directly as a prop to a Client Component!
return <ProfileForm user={user} onUpdateBio={updateBio} />;
}Every client-invoked Server Function in Dinou routes through an internal, optimized Flight RPC bridge. To prevent arbitrary code execution and protect private backend utilities, Dinou strictly validates every incoming request against a compiled server-functions-manifest.json.
Reachability, tree-shaking, and the boundary rules governing server-functions-manifest.json
During build and development, Dinou's AST entry crawler traverses the application dependency tree (ignoring underscore-escaped _folder directories) starting strictly from:
page.tsx, layout.tsx, page_functions.ts, and layout_functions.ts)."use client")._folder), it is excluded: Nothing in an orphan file is ever added to the manifest, and underscore-escaped paths inside src/_private/... are blocked at both compile time and runtime (403 Forbidden)—unreachable code has a 0% HTTP attack surface."use server" at line 1)function helper()) are never added to the manifest and are completely shielded from remote HTTP execution."use server" in their body enter the manifest. Utilities without the directive (e.g. calculateTax) are never registered."use server" are auto-exported by Dinou's AST compiler so the ESM dynamic loader can invoke them when dispatched.This matrix defines exactly how Dinou evaluates any function across your codebase:
| Scenario / Code Pattern | Module Reachable? | Directive Location | Source Export? | Auto-Exported? | In Manifest? | Remotely Callable? |
|---|---|---|---|---|---|---|
| Orphan Module (Never imported) | No | Anywhere | Yes / No | No | No (0%) | 400 Bad Request |
| Module-Level: Exported Function | Yes | Line 1 of file | Yes | N/A | Yes | Allowed (200) |
| Module-Level: Private Helper | Yes | Line 1 of file | No | No | No | 400 Bad Request |
| Function-Level: Exported Action | Yes | Function body | Yes | N/A | Yes | Allowed (200) |
| Function-Level: Unexported Action | Yes | Function body | No | Yes (AST) | Yes | Allowed (200) |
| Mixed Module: Utility without "use server" | Yes | None | Yes | No | No | 400 Bad Request |
| Mixed Module: Private Helper (No directive) | Yes | None | No | No | No | 400 Bad Request |
When the browser submits a Server Function call to POST /____server_function____ with the action identifier and payload arguments:
Validates Origin against Host / X-Forwarded-Host in production and requires x-server-function-call: "1".
Verifies target stays inside src/, blocks ../ traversal, and rejects underscore-escaped _folder segments.
Ensures both the module path and exact export name exist in server-functions-manifest.json.
Executes inside AsyncLocalStorage (getContext()) and streams the result via React Flight (text/x-component).
getContext() and validate input arguments with schemas (e.g. Zod)."use server" or delete the function. Leaving the directive in a reachable file keeps it registered in the manifest even if uncalled..bind():Component-scope variables captured by inline closures are serialized into the client Flight stream via .bind() and echoed back on invocation. Read secrets at module scope (process.env.*) and compute sensitive pricing or authorization inside the "use server" body.A core design pattern in Dinou and React 19 is passing Server Functions as props from Server Components down to Client Components.
This allows client components to remain purely presentational while server components wire up business logic, route parameters, and closure state:
// src/product/[id]/page.tsx (Server Component)
import type { PageProps } from "./dinou";
import { ProductView } from "./client-view";
import { revalidatePathAction } from "@/actions/revalidate";
import { db } from "@/server/db";
export default async function ProductPage({ params }: PageProps) {
const product = await db.products.find(params.id);
// 1. Inline Server Function capturing public route param (params.id)
async function purchaseProduct(paymentToken: string) {
"use server";
// Compute trusted pricing & discounts inside the server boundary (not via .bind!)
const verifiedDiscount = await getCustomerDiscountFromSession();
return await db.orders.create({
productId: params.id,
discount: verifiedDiscount,
token: paymentToken,
});
}
// 2. Bound Server Function attaching a non-sensitive route path argument
const refreshProduct = revalidatePathAction.bind(null, `/product/${params.id}`);
return (
<ProductView
product={product}
onPurchase={purchaseProduct}
onRefresh={refreshProduct}
/>
);
}// src/product/[id]/client-view.tsx
"use client";
import { useTransition } from "react";
interface Props {
product: { id: string; name: string; price: number };
onPurchase: (token: string) => Promise<{ success: boolean }>;
onRefresh: () => Promise<void>;
}
export function ProductView({ product, onPurchase, onRefresh }: Props) {
const [isPending, startTransition] = useTransition();
const handleBuy = () => {
startTransition(async () => {
const res = await onPurchase("tok_card_visa_1234");
if (res.success) alert("Purchase confirmed!");
});
};
return (
<div className="space-y-4">
<h1 className="text-2xl font-bold">{product.name}</h1>
<p className="text-lg">${product.price}</p>
<div className="flex gap-2">
<button onClick={handleBuy} disabled={isPending} className="btn-primary">
{isPending ? "Processing..." : "Buy Now"}
</button>
<button onClick={() => onRefresh()} className="btn-secondary">
Refresh Data
</button>
</div>
</div>
);
}When Dinou's AST compiler detects "use server" inside a component function:
@babel/traverse to distinguish module-level bindings (such as db or process.env.*, which stay 100% private on the server) from component-level outer variables (such as params).export async function $$dinou_action_purchaseProduct_0(params, paymentToken).$$dinou_action_purchaseProduct_0.bind(null, params).onPurchase(token). Always verify session authorization and sensitive calculations inside the action body.Dinou uniquely allows Server Functions to return fully rendered React component trees directly over Flight RPC—including interactive Client Components and nested Server Actions inside the streamed UI. In Server Components, the component is awaited directly inside native <Suspense>; in Client Components, the returned promise is unwrapped with React 19's use() hook:
// src/actions/get-post-card.tsx
"use server"; // 👈 Module-level directive in Dinou
import db from "@/lib/db";
import { PostCard } from "@/components/post-card";
export async function getPostCard(postId: string) {
const post = await db.posts.findUnique({ where: { id: postId } });
if (!post) throw new Error("Post not found");
// Returns a rendered JSX component directly over Flight RPC!
return <PostCard post={post} />;
}// src/blog/page.tsx
// Server Component: directly await the Server Function with React 19 Suspense
import { Suspense } from "react";
import { getPostCard } from "@/actions/get-post-card";
async function PostSlot({ id }: { id: string }) {
// Directly awaited on the server during SSR / streaming
return await getPostCard(id);
}
export default function BlogPage() {
return (
<section className="space-y-4">
<h1 className="text-2xl font-bold">Featured Story</h1>
{/* Native React 19 Suspense fallback */}
<Suspense fallback={<div className="skeleton h-48 w-full rounded" />}>
<PostSlot id="post-101" />
</Suspense>
</section>
);
}// src/blog/page.tsx
// Client Component: unwrap the Flight RPC promise with React 19 use()
"use client";
import { useState, use, Suspense } from "react";
import { getPostCard } from "@/actions/get-post-card";
function PostStream({ promise }: { promise: Promise<React.ReactNode> }) {
// Pure React 19 'use()' unrolls the promise within Suspense
const content = use(promise);
return <>{content}</>;
}
export default function BlogPage() {
const [postId, setPostId] = useState("post-1");
const [postPromise, setPostPromise] = useState(() => getPostCard("post-1"));
const loadPost = (id: string) => {
setPostId(id);
setPostPromise(getPostCard(id));
};
return (
<section className="space-y-4">
<h1 className="text-2xl font-bold">Featured Story</h1>
<div className="flex gap-2">
<button onClick={() => loadPost("post-1")} className="btn">Post 1</button>
<button onClick={() => loadPost("post-2")} className="btn">Post 2</button>
</div>
{/* Re-suspends cleanly on promise update */}
<Suspense key={postId} fallback={<p>Streaming post from server...</p>}>
<PostStream promise={postPromise} />
</Suspense>
</section>
);
}Directly await the Server Function inside an async component. React streams HTML progressively as promises resolve.
use())Dispatches Flight RPC returning a Promise. React 19's native use(promise) unrolls it synchronously inside <Suspense> without external state libraries.
Server Functions passed to the action prop of a <form> or formAction of a button act as Server Actions.
Server Actions can be declared either as dedicated action files or inline within Server Components and mixed modules. You can pass them directly to the action attribute of a <form> in both Server Components and Client Components:
// src/newsletter/page.tsx
// Server Component (invoking Server Action directly)
import { subscribeNewsletter } from "@/actions/subscribe";
export default function NewsletterPage() {
return (
<form action={subscribeNewsletter} className="flex gap-2">
<input name="email" type="email" placeholder="[email protected]" required className="input" />
<button type="submit" className="btn-primary">Subscribe</button>
</form>
);
}// src/actions/subscribe.ts
"use server"; // Module-level or function-level directive
import db from "@/lib/db";
export async function subscribeNewsletter(formData: FormData) {
const email = formData.get("email") as string;
await db.subscribers.create({ data: { email } });
}You can define form actions in dedicated files using module-level "use server", or inline inside Server Components using function-level "use server" (as detailed in Section 1 and Section 2). In both cases, submitting the form transparently dispatches a Flight RPC request validated against server-functions-manifest.json.
subscribeNewsletter return? (Understanding void / undefined)This action returns Promise<void>, which resolves to undefined. In pure React 19 form actions (<form action={subscribeNewsletter}>), this is completely standard for fire-and-forget mutations: the browser submits the form data, the server executes the database write, and no state payload is needed by the UI.
When should a Server Action return a value? If your UI needs to display interactive feedback (such as "Subscribed successfully!" or validation errors), the action should return a serializable payload (e.g. { success: true, message: "..." }) and be wired to React 19's useActionState hook (as explained in Section 5.2 below). Other common patterns include performing a server-side redirect() or calling revalidatePath() before completing.
useActionState & useFormStatusFor rich interactive forms with validation feedback and loading spinners, use React 19's standard hooks:
<form> without prop drilling.// src/components/create-post-form.tsx
"use client";
import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { createPostAction, type FormState } from "@/actions/posts";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} className="btn-primary">
{pending ? "Saving..." : "Publish Post"}
</button>
);
}
const initialState: FormState = { success: false, message: "" };
export function CreatePostForm() {
// useActionState binds the server action to form state and tracks submission
const [state, formAction, isPending] = useActionState(createPostAction, initialState);
return (
<form action={formAction} className="flex flex-col gap-4">
{state.message && (
<div className={state.success ? "text-green-500" : "text-red-500"}>
{state.message}
</div>
)}
<input name="title" placeholder="Post title" required className="input" />
<textarea name="content" placeholder="Write content..." required className="textarea" />
<SubmitButton />
</form>
);
}// src/actions/posts.ts
"use server";
import db from "@/lib/db";
export type FormState = {
success: boolean;
message: string;
};
// Server Action receives (prevState, formData) when bound to useActionState
export async function createPostAction(
prevState: FormState,
formData: FormData
): Promise<FormState> {
const title = (formData.get("title") as string)?.trim();
const content = (formData.get("content") as string)?.trim();
if (!title || title.length < 3) {
return { success: false, message: "Title must be at least 3 characters." };
}
if (!content) {
return { success: false, message: "Content cannot be empty." };
}
await db.posts.create({ data: { title, content } });
return { success: true, message: "Post published successfully!" };
}useOptimisticWith React 19's useOptimistic, you can update the user interface immediately before the server responds:
// src/components/like-button.tsx
"use client";
import { useOptimistic, useTransition } from "react";
import { toggleLikeAction } from "@/actions/likes";
export function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {
const [isPending, startTransition] = useTransition();
const [optimisticLikes, setOptimisticLikes] = useOptimistic(
initialLikes,
(current, update: number) => current + update
);
const handleClick = () => {
startTransition(async () => {
setOptimisticLikes(1); // Optimistically increment in 0ms on client
await toggleLikeAction(postId); // Dispatches Server Action via Flight RPC
});
};
return (
<button onClick={handleClick} disabled={isPending} className="btn-like">
❤️ {optimisticLikes}
</button>
);
}// src/actions/likes.ts
"use server";
import db from "@/lib/db";
export async function toggleLikeAction(postId: string) {
// Updates like count on the database
await db.posts.update({
where: { id: postId },
data: { likes: { increment: 1 } },
});
return { success: true };
}<Suspense> boundary here?<Suspense> only activates when a component suspends (by throwing a pending Promise, such as with React.use(promise) or an async Server Component).
In contrast, useOptimistic does the exact opposite of suspending: it synchronously paints the temporary new value (e.g. switching immediately from 10 to 11) in 0ms on the client, avoiding loading spinners or skeleton fallbacks entirely while the Server Action runs in the background. It relies strictly on React 19 transitions (useTransition or Form Actions). If the server call succeeds, React seamlessly commits the real server state; if it fails, React automatically rolls back to the initial value with zero boilerplate.
getContext)Dinou provides getContext() (exported from "dinou/server", "dinou", and contextual "./dinou") to access the underlying request and response lifecycle synchronously within any Server Function or SSR component. For the complete guide covering Server Components, SSG/PPR bailout rules, unified multi-runtime env bindings, and plugin state, see Request Context (getContext).
context.req.cookies: Dictionary of incoming client cookies (e.g. cookies["auth_token"]).context.req.headers: Incoming HTTP headers dictionary.context.req.query: URL search parameters.context.res.cookie(name, value, options): Sets an HTTP Set-Cookie header before streaming begins (supporting httpOnly, secure, sameSite, maxAge, etc.; if invoked mid-stream after headers are sent, non-httpOnly cookies still sync automatically via Flight stream commands).context.res.clearCookie(name, options): Clears a cookie from the client.context.env / context.ctx & Plugin State: Exposes Edge/Cloudflare bindings as well as custom properties attached by onRequest plugins.// src/actions/auth-check.ts
"use server";
import { getContext } from "dinou/server";
export async function getCurrentUser() {
const context = getContext();
const sessionToken = context.req.cookies["session_token"];
const userAgent = context.req.headers["user-agent"];
if (!sessionToken) return null;
return await verifySession(sessionToken);
}// src/actions/login.ts
"use server";
import { getContext } from "dinou/server";
export async function loginAction(formData: FormData) {
const context = getContext();
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const session = await authenticateUser(email, password);
// Set secure HTTP-only session cookie
context.res.cookie("session_token", session.token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7, // 7 days in seconds
path: "/",
});
return { success: true };
}
export async function logoutAction() {
const context = getContext();
// Clear the cookie upon logout
context.res.clearCookie("session_token", { path: "/" });
return { success: true };
}redirect)Dinou provides a universal redirect(destination) utility exported from "dinou" (and contextual "./dinou"):
router.replace()) without reloading the page.// src/actions/checkout.ts
"use server";
import { redirect } from "dinou";
import db from "@/lib/db";
export async function completeOrder(orderId: string) {
await db.orders.updateStatus(orderId, "PAID");
// Supports both absolute internal paths ("/checkout/...") and relative paths ("./success")
return redirect(`/checkout/${orderId}/success`);
}redirect() in Server Functionstry / catch: Inside a Server Function, redirect() throws an internal control-flow signal (dinou-internal-redirect). Call return redirect(...) outside try / catch blocks (or rethrow if err?.$$type === "dinou-internal-redirect").redirect("./success"); Dinou resolves them automatically against the caller's current route (x-dinou-current-path).redirect() enforces internal application paths (/path, rejecting protocol-relative //evil.com or external origins by falling back to "/").A foundational question when handling redirects across hybrid architectures is: How does Dinou determine whether redirect() issues an HTTP 302 vs. a client-side transition, and is calling redirect() in a Server Component equivalent to invoking it via a Server Function?
Calling redirect() directly inside a Server Component vs. calling an imported Server Function (e.g., await verifyUser()) from that Server Component is functionally identical. Because both run inside the same server runtime during the same SSR request lifecycle, they share the exact same request context and streaming state.
Occurs inside getProps() in page_functions.ts, at the top level of the root page.tsx Server Component (outside any <Suspense> boundary), or in a global plugin hook (onRequest) in dinou.config.ts.
Because zero HTML bytes have reached the wire (headersSent === false), Dinou issues a clean HTTP 302 with a Location header. Crucial for SEO crawlers and search indexers.
// src/dashboard/page_functions.ts
import { redirect, getContext } from "./dinou";
export async function getProps() {
const ctx = getContext();
if (!ctx.req.cookies.session_token) {
// Evaluated before page rendering -> HTTP 302 redirect (or x-rsc-redirect on SPA nav)
return redirect("/login");
}
return { user: { name: "Alex" } };
}// src/dashboard/page.tsx (Server Component root)
import { redirect, getContext } from "./dinou";
export default async function DashboardPage() {
const ctx = getContext();
if (!ctx.req.cookies.session_token) {
// At root before stream begins -> HTTP 302 redirect
return redirect("/login");
}
return <h1>Welcome to Dashboard</h1>;
}// dinou.config.ts (Global Plugin Hook)
import { defineConfig } from "dinou/config";
export default defineConfig({
plugins: [
{
name: "auth-guard",
async onRequest(request, context) {
// context.req.path is normalized ("/dashboard" even on SPA RSC fetches)
// and Response.redirect() auto-translates to x-rsc-redirect for <Link> navigations
if (context.req.path.startsWith("/dashboard") && !context.req.cookies.session_token) {
return Response.redirect(new URL("/login", request.url), 302);
}
},
},
],
});Occurs inside an async child wrapped in <Suspense fallback={<Skeleton />}>. React opens the HTTP connection with status 200 OK immediately to stream the initial shell.
At HTTP protocol level, an open 200 OK stream cannot turn into a 302. Dinou safely emits <ClientRedirect />, completing the transition upon browser hydration without breaking the stream.
// src/reports/page.tsx (Server Component)
import { Suspense } from "react";
import { redirect } from "dinou";
async function RestrictedReport() {
const isAllowed = await checkUserAccess();
if (!isAllowed) {
// 200 OK stream already open -> <ClientRedirect />
return redirect("/unauthorized");
}
return <div>Financial Metrics</div>;
}
export default function Page() {
return (
<Suspense fallback={<p>Loading financial report...</p>}>
<RestrictedReport />
</Suspense>
);
}Triggered from browser interactions (form actions or button clicks) via a dedicated POST request.
Dinou executes the server mutation and intercepts redirect() before streaming (headers unsent), returning redirect metadata. The client proxy navigates via the SPA router without a full page reload.
// src/actions/cart.ts
"use server";
import { redirect } from "dinou";
import db from "@/lib/db";
export async function checkoutAction(formData: FormData) {
const order = await db.orders.create({ ... });
// Dedicated POST: soft SPA navigation in browser
return redirect(`/checkout/${order.id}/success`);
}When called directly inside a client component during browser rendering, no network request is sent to the server.
Dinou immediately delegates to router.replace() in the client SPA router, smoothly updating the URL and view in 0ms without a page reload.
// src/components/client-guard.tsx
"use client";
import { redirect } from "dinou";
export function ClientGuard({ isAllowed }: { isAllowed: boolean }) {
if (!isAllowed) {
// In-browser render: executes router.replace() in SPA router
return redirect("/forbidden");
}
return <button className="btn">Control Panel</button>;
}| Invocation Context | Headers Sent? | Resulting Mechanism | Recommended For |
|---|---|---|---|
| 1. SSR Root (page_functions.ts, page.tsx, Plugin) | No | Hard HTTP Redirect (Status 302) Server issues an | Auth guards (getProps), root guards, global middleware plugins, SEO canonicals |
| 2. SSR: Deferred (<Suspense>) | Yes(200 OK stream open) | Streaming Fallback ( <ClientRedirect />)Because the | Deferred conditional access, late data-dependent checks inside Suspense |
| 3. Server Function (from Client Action) | No(standard POST) | Soft SPA Navigation (Status 200) Server returns HTTP | Form submissions, shopping cart checkout, stateful mutations |
| 4. Client Component (Render) | N/A(in-browser) | Client Router Replacement ( router.replace())Executes 100% in the browser with zero server roundtrip. Immediately dispatches | Pure UI state redirection, client-side permission gates |
Learn how to purge stale SSG pages, layouts, and ISR cache slots on-demand using revalidatePage, revalidateLayout, revalidatePath, and revalidateTag in the dedicated guide.