Server Actions
Learn how to implement public, protected, and paid Server Actions for data mutations.
Server Actions allow you to define functions that run directly on the server, typically triggered by form submissions or client-side events, without needing to create separate API endpoints. They are defined using the "use server";
directive at the top of the file or function.
Public Server Action
These actions can be called by anyone, authenticated or not.
Example Backend Action (app/actions/feedback.ts
):
Example Frontend Invocation (useTransition
):
Protected Server Action
Always Check Authentication!
While your UI might prevent unauthenticated users from reaching a component, Server Actions are like API endpoints and can be triggered directly. It is critical to ALWAYS perform an authentication check (e.g., using getCurrentUser
) inside every Server Action that requires a logged-in user. Do not rely solely on UI-level restrictions.
These actions require the user to be authenticated.
Automatic Session Handling
NextAuth.js handles session management for Server Actions called from the
client automatically. The getCurrentUser
helper will correctly identify the
logged-in user.
Example Backend Action (app/actions/profile.ts
):
Example Frontend Invocation (useActionState
):
Paid Server Action
Always Check Authorization!
Similar to authentication, even if your UI prevents users without access from reaching a component, the Server Action itself can be triggered directly. It is critical to ALWAYS perform authorization checks (e.g., verifying user.hasAccess
or specific permissions) inside every Server Action that requires specific access rights. Do not rely solely on UI restrictions.
These actions require authentication AND specific access rights (e.g., an active subscription).
Checking Access Efficiently
Ensure your getCurrentUser
helper method return currentUser which already
has hasAccess field.
Example Backend Action (app/actions/premium.ts
):
Example Frontend Invocation (useActionState
):