Server Actions
Server actions are defined in a separate .ts
file marked with the 'use server'
directive.
This tells React what is in that file can only run on the server, and can be called from a client component:
//actions.ts
'use server'
async function myServerAction(formData) => {
//we are on the server, we can directly
//do something with the form data
}
In a client component:
'use client'
import { myServerAction } from './actions'
export const Demo = () => {
return (
<div>
<form action={myServerAction}>
<input
type='text'
name='fullName'
/>
<button type='submit'>Submit</button>
</form>
</div>
)
}
→ Get my React Beginner's Handbook
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025