Form actions with server functions let you handle form data directly on the server. This makes your app faster and more secure by avoiding extra client-side code.
Form actions with server functions in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
import { redirect } from 'next/navigation' export async function action(formData: FormData) { // process formData here return redirect('/thank-you') } export default function Page() { return ( <form action={action} method="post"> <input name="name" type="text" required /> <button type="submit">Send</button> </form> ) }
The action function runs on the server when the form is submitted.
Use formData.get('fieldName') to access form values inside the action.
export async function action(formData: FormData) { const name = formData.get('name') console.log('Name:', name) return new Response('Form received') } export default function Page() { return ( <form action={action} method="post"> <input name="name" type="text" /> <button type="submit">Submit</button> </form> ) }
import { redirect } from 'next/navigation' export async function action(formData: FormData) { const email = formData.get('email') // Save email to database here return redirect('/welcome') } export default function Page() { return ( <form action={action} method="post"> <input name="email" type="email" required /> <button type="submit">Register</button> </form> ) }
This is a simple contact form. When submitted, the message is sent to the server function action. The server logs the message and then redirects the user to a thank-you page.
import { redirect } from 'next/navigation' export async function action(formData: FormData) { const message = formData.get('message') console.log('Received message:', message) // Here you could save the message to a database return redirect('/thank-you') } export default function ContactForm() { return ( <main> <h1>Contact Us</h1> <form action={action} method="post"> <label htmlFor="message">Your Message:</label> <textarea id="message" name="message" required rows={4} cols={40}></textarea> <button type="submit">Send</button> </form> </main> ) }
Server functions run only on the server, so you cannot use browser APIs inside them.
Use redirect() from next/navigation to send users to another page after form submission.
Always add method="post" to your form to send data securely.
Form actions let you handle form data on the server in Next.js App Router.
Use action functions to process form data and respond or redirect.
This approach keeps your app secure and simple by avoiding client-side form logic.
Practice
form actions with server functions in Next.js App Router?Solution
Step 1: Understand form actions role
Form actions in Next.js let you handle form data processing on the server side, improving security and simplicity.Step 2: Compare with client-side logic
Unlike client-side validation or styling, form actions avoid running JavaScript in the browser for form handling.Final Answer:
To handle form submissions securely on the server without client-side JavaScript -> Option DQuick Check:
Form actions = server-side handling [OK]
- Thinking form actions run client-side
- Confusing form styling with form handling
- Assuming form actions fetch external APIs on client
Solution
Step 1: Identify server action syntax
Server actions are async functions exported to handle form data, receivingformDataas parameter.Step 2: Check other options
Other options either return JSX incorrectly or use client-side code like alert or console.log without async/await.Final Answer:
export async function action(formData) { /* handle data */ } -> Option AQuick Check:
Server action = async export function [OK]
- Defining action as a React component
- Using alert or console.log inside server action
- Not marking function as async
export async function action(formData) {
const name = formData.get('name');
return new Response(`Hello, ${name}!`);
}Solution
Step 1: Extract form data value
The function usesformData.get('name')to get the input named 'name'.Step 2: Return a Response with greeting
The function returns a Response object with a greeting message including the name value.Final Answer:
The server responds with 'Hello, [name]!' where [name] is the input value -> Option CQuick Check:
formData.get + Response = greeting message [OK]
- Assuming Response is invalid in server action
- Thinking form data is ignored
- Expecting page reload without message
export async function action(formData) {
const email = formData.email;
return new Response(`Email: ${email}`);
}Solution
Step 1: Check how formData is accessed
formData is a FormData object; to get values, useformData.get('fieldName'), not dot notation.Step 2: Validate other parts
The function is async and exported correctly; returning Response is allowed in server actions.Final Answer:
Using formData.email instead of formData.get('email') -> Option BQuick Check:
Access formData with get() method [OK]
- Accessing formData fields with dot notation
- Forgetting async keyword
- Thinking Response cannot be returned
export async function action(formData) {
const feedback = formData.get('feedback');
// Save feedback to database (omitted)
return redirect('/thank-you');
}Solution
Step 1: Verify form data retrieval
The code correctly usesformData.get('feedback')to get the input value.Step 2: Confirm redirect usage
Next.js server actions support returningredirect()to navigate after processing.Final Answer:
This code correctly handles form data and redirects after submission -> Option AQuick Check:
formData.get + redirect() = correct pattern [OK]
- Thinking redirect() is not allowed in server actions
- Accessing formData with dot notation
- Believing server actions cannot save data or cause side effects
