Bird
Raised Fist0
NextJSframework~10 mins

Form actions with server functions in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Form actions with server functions
User fills form
User submits form
Form data sent to server function
Server function processes data
Server sends response
Client updates UI based on response
This flow shows how a form submission triggers a server function that processes data and sends back a response to update the UI.
Execution Sample
NextJS
export default function Page() {
  async function handleSubmit(formData) {
    'use server'
    console.log('Received:', formData.get('name'))
  }
  return (
    <form action={handleSubmit}>
      <input name="name" />
      <button type="submit">Send</button>
    </form>
  )
}
A Next.js form uses a server function as its action to handle submission and log the input value.
Execution Table
StepActionForm DataServer Function CalledConsole OutputUI Update
1User types 'Alice' in inputname=AliceNoInput shows 'Alice'
2User clicks submit buttonname=AliceYesReceived: AliceForm submits, page may refresh or update
3Server function logs dataname=AliceYesReceived: AliceServer processes data
4Server sends responsename=AliceYesUI updates based on response
5Form submission endsNoReady for next input
💡 Form submission completes after server function processes data and UI updates.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
formDataemptyname=Alicename=Alicename=Alicecleared or unchanged
serverFunctionCalledfalsefalsetruetruefalse after completion
Key Moments - 3 Insights
Why does the server function run only after form submission?
Because the server function is assigned as the form's action, it triggers only when the user submits the form, as shown in execution_table step 2.
How does the form data reach the server function?
The form data is automatically collected and passed as a FormData object to the server function when the form submits, visible in execution_table step 2 and 3.
Does the UI update immediately after submission?
The UI updates after the server sends a response, which may cause a page refresh or partial update, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the server function called?
AStep 5
BStep 1
CStep 2
DStep 4
💡 Hint
Check the 'Server Function Called' column in the execution_table.
According to the variable tracker, what is the value of formData after step 3?
Aname=Alice
Bcleared
Cempty
Dundefined
💡 Hint
Look at the 'formData' row in variable_tracker after step 3.
If the user changes the input to 'Bob' before submitting, what changes in the execution table?
AServer function is not called
BConsole Output changes to 'Received: Bob'
CUI does not update
DForm data remains 'name=Alice'
💡 Hint
Refer to the 'Console Output' column in execution_table step 3.
Concept Snapshot
Next.js form actions use server functions to handle submissions.
Assign the server function to the form's action attribute.
Form data is passed as FormData to the server function.
Server processes data and can update UI or redirect.
This enables server-side logic without client JS handlers.
Full Transcript
This visual execution shows how a Next.js form uses a server function as its action. The user types a name, submits the form, which triggers the server function. The server function receives the form data as a FormData object and logs the input value. After processing, the server sends a response that updates the UI or refreshes the page. Variables like formData and serverFunctionCalled change state during these steps. Key moments clarify when the server function runs and how data flows. Quiz questions test understanding of these steps.

Practice

(1/5)
1. What is the main purpose of using form actions with server functions in Next.js App Router?
easy
A. To fetch data from an external API on the client
B. To run client-side validation before submitting the form
C. To style the form elements dynamically
D. To handle form submissions securely on the server without client-side JavaScript

Solution

  1. 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.
  2. Step 2: Compare with client-side logic

    Unlike client-side validation or styling, form actions avoid running JavaScript in the browser for form handling.
  3. Final Answer:

    To handle form submissions securely on the server without client-side JavaScript -> Option D
  4. Quick Check:

    Form actions = server-side handling [OK]
Hint: Form actions run on server, not client [OK]
Common Mistakes:
  • Thinking form actions run client-side
  • Confusing form styling with form handling
  • Assuming form actions fetch external APIs on client
2. Which of the following is the correct way to define a server action function for a form in Next.js?
easy
A. export async function action(formData) { /* handle data */ }
B. function action() { return }
C. const action = () => console.log('submit')
D. export default function action() { alert('submitted') }

Solution

  1. Step 1: Identify server action syntax

    Server actions are async functions exported to handle form data, receiving formData as parameter.
  2. Step 2: Check other options

    Other options either return JSX incorrectly or use client-side code like alert or console.log without async/await.
  3. Final Answer:

    export async function action(formData) { /* handle data */ } -> Option A
  4. Quick Check:

    Server action = async export function [OK]
Hint: Server actions are async exported functions with formData param [OK]
Common Mistakes:
  • Defining action as a React component
  • Using alert or console.log inside server action
  • Not marking function as async
3. Given this server action function in Next.js, what will be the output after submitting the form?
export async function action(formData) {
  const name = formData.get('name');
  return new Response(`Hello, ${name}!`);
}
medium
A. The page will reload without any message
B. The form data is ignored and no response is sent
C. The server responds with 'Hello, [name]!' where [name] is the input value
D. A syntax error occurs because Response is not allowed

Solution

  1. Step 1: Extract form data value

    The function uses formData.get('name') to get the input named 'name'.
  2. Step 2: Return a Response with greeting

    The function returns a Response object with a greeting message including the name value.
  3. Final Answer:

    The server responds with 'Hello, [name]!' where [name] is the input value -> Option C
  4. Quick Check:

    formData.get + Response = greeting message [OK]
Hint: formData.get returns input value used in Response [OK]
Common Mistakes:
  • Assuming Response is invalid in server action
  • Thinking form data is ignored
  • Expecting page reload without message
4. Identify the error in this Next.js server action function:
export async function action(formData) {
  const email = formData.email;
  return new Response(`Email: ${email}`);
}
medium
A. Response object cannot be returned from server actions
B. Using formData.email instead of formData.get('email')
C. Missing async keyword in function declaration
D. Function should not be exported

Solution

  1. Step 1: Check how formData is accessed

    formData is a FormData object; to get values, use formData.get('fieldName'), not dot notation.
  2. Step 2: Validate other parts

    The function is async and exported correctly; returning Response is allowed in server actions.
  3. Final Answer:

    Using formData.email instead of formData.get('email') -> Option B
  4. Quick Check:

    Access formData with get() method [OK]
Hint: Use formData.get('field') to access form values [OK]
Common Mistakes:
  • Accessing formData fields with dot notation
  • Forgetting async keyword
  • Thinking Response cannot be returned
5. You want to create a Next.js form that submits user feedback and then redirects to a thank-you page using a server action. Which code snippet correctly implements this behavior?
export async function action(formData) {
  const feedback = formData.get('feedback');
  // Save feedback to database (omitted)
  return redirect('/thank-you');
}
hard
A. This code correctly handles form data and redirects after submission
B. You cannot use redirect in server actions; must return JSON instead
C. The formData.get call should be replaced with formData.feedback
D. Server actions cannot perform side effects like saving data

Solution

  1. Step 1: Verify form data retrieval

    The code correctly uses formData.get('feedback') to get the input value.
  2. Step 2: Confirm redirect usage

    Next.js server actions support returning redirect() to navigate after processing.
  3. Final Answer:

    This code correctly handles form data and redirects after submission -> Option A
  4. Quick Check:

    formData.get + redirect() = correct pattern [OK]
Hint: Use redirect() in server action to navigate after submit [OK]
Common Mistakes:
  • Thinking redirect() is not allowed in server actions
  • Accessing formData with dot notation
  • Believing server actions cannot save data or cause side effects