--- title: How to create forms with Server Actions nav_title: Forms description: Learn how to create forms in Next.js with React Server Actions. --- React Server Actions are [Server Functions](https://react.dev/reference/rsc/server-functions) that execute on the server. They can be called in Server and Client Components to handle form submissions. This guide will walk you through how to create forms in Next.js with Server Actions. ## How it works React extends the HTML [`
`](https://developer.mozilla.org/docs/Web/HTML/Element/form) element to allow Server Actions to be invoked with the [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form#action) attribute. When used in a form, the function automatically receives the [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData/FormData) object. You can then extract the data using the native [`FormData` methods](https://developer.mozilla.org/en-US/docs/Web/API/FormData#instance_methods): ```tsx filename="app/invoices/page.tsx" switcher export default function Page() { async function createInvoice(formData: FormData) { 'use server' const rawFormData = { customerId: formData.get('customerId'), amount: formData.get('amount'), status: formData.get('status'), } // mutate data // revalidate the cache } return ...
} ``` ```jsx filename="app/invoices/page.js" switcher export default function Page() { async function createInvoice(formData) { 'use server' const rawFormData = { customerId: formData.get('customerId'), amount: formData.get('amount'), status: formData.get('status'), } // mutate data // revalidate the cache } return
...
} ``` > **Good to know:** When working with forms that have multiple fields, you can use the [`entries()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries) method with JavaScript's [`Object.fromEntries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries). For example: `const rawFormData = Object.fromEntries(formData)`. ## Passing additional arguments Outside of form fields, you can pass additional arguments to a Server Function using the JavaScript [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) method. For example, to pass the `userId` argument to the `updateUser` Server Function: ```tsx filename="app/client-component.tsx" highlight={6} switcher 'use client' import { updateUser } from './actions' export function UserProfile({ userId }: { userId: string }) { const updateUserWithId = updateUser.bind(null, userId) return (
) } ``` ```jsx filename="app/client-component.js" highlight={6} switcher 'use client' import { updateUser } from './actions' export function UserProfile({ userId }) { const updateUserWithId = updateUser.bind(null, userId) return (
) } ``` The Server Function will receive the `userId` as an additional argument: ```ts filename="app/actions.ts" switcher 'use server' export async function updateUser(userId: string, formData: FormData) {} ``` ```js filename="app/actions.js" switcher 'use server' export async function updateUser(userId, formData) {} ``` > **Good to know**: > > - An alternative is to pass arguments as hidden input fields in the form (e.g. ``). However, the value will be part of the rendered HTML and will not be encoded. > - `bind` works in both Server and Client Components and supports progressive enhancement. ## Form validation Forms can be validated on the client or server. - For **client-side validation**, you can use the HTML attributes like `required` and `type="email"` for basic validation. - For **server-side validation**, you can use a library like [zod](https://zod.dev/) to validate the form fields. For example: ```tsx filename="app/actions.ts" switcher 'use server' import { z } from 'zod' const schema = z.object({ email: z.string({ invalid_type_error: 'Invalid Email', }), }) export default async function createUser(formData: FormData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) // Return early if the form data is invalid if (!validatedFields.success) { return { errors: validatedFields.error.flatten().fieldErrors, } } // Mutate data } ``` ```jsx filename="app/actions.js" switcher 'use server' import { z } from 'zod' const schema = z.object({ email: z.string({ invalid_type_error: 'Invalid Email', }), }) export default async function createsUser(formData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) // Return early if the form data is invalid if (!validatedFields.success) { return { errors: validatedFields.error.flatten().fieldErrors, } } // Mutate data } ``` ## Validation errors To display validation errors or messages, turn the component that defines the `
` into a Client Component and use React [`useActionState`](https://react.dev/reference/react/useActionState). When using `useActionState`, the Server function signature will change to receive a new `prevState` or `initialState` parameter as its first argument. ```tsx filename="app/actions.ts" highlight={4} switcher 'use server' import { z } from 'zod' export async function createUser(initialState: any, formData: FormData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) // ... } ``` ```jsx filename="app/actions.ts" highlight={4} switcher 'use server' import { z } from 'zod' // ... export async function createUser(initialState, formData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) // ... } ``` You can then conditionally render the error message based on the `state` object. ```tsx filename="app/ui/signup.tsx" highlight={11,18-20} switcher 'use client' import { useActionState } from 'react' import { createUser } from '@/app/actions' const initialState = { message: '', } export function Signup() { const [state, formAction, pending] = useActionState(createUser, initialState) return ( {/* ... */}

{state?.message}

) } ``` ```jsx filename="app/ui/signup.js" highlight={11,18-20} switcher 'use client' import { useActionState } from 'react' import { createUser } from '@/app/actions' const initialState = { message: '', } export function Signup() { const [state, formAction, pending] = useActionState(createUser, initialState) return (
{/* ... */}

{state?.message}

) } ``` ## Pending states The [`useActionState`](https://react.dev/reference/react/useActionState) hook exposes a `pending` boolean that can be used to show a loading indicator or disable the submit button while the action is being executed. ```tsx filename="app/ui/signup.tsx" highlight={7,12} switcher 'use client' import { useActionState } from 'react' import { createUser } from '@/app/actions' export function Signup() { const [state, formAction, pending] = useActionState(createUser, initialState) return (
{/* Other form elements */}
) } ``` ```jsx filename="app/ui/signup.js" highlight={7,12} switcher 'use client' import { useActionState } from 'react' import { createUser } from '@/app/actions' export function Signup() { const [state, formAction, pending] = useActionState(createUser, initialState) return (
{/* Other form elements */}
) } ``` Alternatively, you can use the [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) hook to show a loading indicator while the action is being executed. When using this hook, you'll need to create a separate component to render the loading indicator. For example, to disable the button when the action is pending: ```tsx filename="app/ui/button.tsx" highlight={6} switcher 'use client' import { useFormStatus } from 'react-dom' export function SubmitButton() { const { pending } = useFormStatus() return ( ) } ``` ```jsx filename="app/ui/button.js" highlight={6} switcher 'use client' import { useFormStatus } from 'react-dom' export function SubmitButton() { const { pending } = useFormStatus() return ( ) } ``` You can then nest the `SubmitButton` component inside the form: ```tsx filename="app/ui/signup.tsx" switcher import { SubmitButton } from './button' import { createUser } from '@/app/actions' export function Signup() { return (
{/* Other form elements */} ) } ``` ```jsx filename="app/ui/signup.js" switcher import { SubmitButton } from './button' import { createUser } from '@/app/actions' export function Signup() { return (
{/* Other form elements */} ) } ``` > **Good to know:** In React 19, `useFormStatus` includes additional keys on the returned object, like data, method, and action. If you are not using React 19, only the `pending` key is available. ## Optimistic updates You can use the React [`useOptimistic`](https://react.dev/reference/react/useOptimistic) hook to optimistically update the UI before the Server Function finishes executing, rather than waiting for the response: ```tsx filename="app/page.tsx" switcher 'use client' import { useOptimistic } from 'react' import { send } from './actions' type Message = { message: string } export function Thread({ messages }: { messages: Message[] }) { const [optimisticMessages, addOptimisticMessage] = useOptimistic< Message[], string >(messages, (state, newMessage) => [...state, { message: newMessage }]) const formAction = async (formData: FormData) => { const message = formData.get('message') as string addOptimisticMessage(message) await send(message) } return (
{optimisticMessages.map((m, i) => (
{m.message}
))}
) } ``` ```jsx filename="app/page.js" switcher 'use client' import { useOptimistic } from 'react' import { send } from './actions' export function Thread({ messages }) { const [optimisticMessages, addOptimisticMessage] = useOptimistic( messages, (state, newMessage) => [...state, { message: newMessage }] ) const formAction = async (formData) => { const message = formData.get('message') addOptimisticMessage(message) await send(message) } return (
{optimisticMessages.map((m) => (
{m.message}
))}
) } ``` ## Nested form elements You can call Server Actions in elements nested inside `
` such as `