Creating a server action
Create an actions file
Create a file in
app/actions/ and mark it with 'use server':app/actions/form-actions.js
Complete form example
Here’s the full form demo from the COSMOS RSC source:app/pages/features/forms.js
Working with FormData
Server actions receive aFormData object. Extract values using get() or getAll():
Validation and error handling
Return validation errors from your action:Using server APIs
Server actions can access server-only APIs:Progressive enhancement
Forms with server actions work without JavaScript enabled. The browser will fall back to a standard form submission:Best practices
Always validate on the server
Always validate on the server
Never trust client-side data. Always validate in your server action, even if you also validate on the client.
Use meaningful return values
Use meaningful return values
Return structured data from actions to provide feedback:
Handle errors gracefully
Handle errors gracefully
Wrap database operations in try/catch:
Keep actions focused
Keep actions focused
Create separate action functions for different forms rather than one large handler: