1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Server Actions
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
06Hrs
27Mins
07Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Server Actions

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
06Hrs
27Mins
07Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Server Actions

Overview

If Server Components are the modern way to read data from the backend, Server Actions are the modern way to write data to the backend (e.g., submitting forms, updating databases).

Historically, to handle a form submission in React, you had to: 1. Create a useState controlled form. 2. Write a separate Express.js or Next.js API Route (e.g., /api/submit). 3. Use fetch() in the component to send a JSON POST request to that URL.

Server Actions eliminate this entire process. A Server Action is literally an asynchronous JavaScript function defined with the `"use server"` directive. You can pass this function directly to the action attribute of an HTML <form>. When the user clicks submit, React automatically encrypts the form data, bridges the network gap, and executes your backend function directly on the server.

Syntax

Submitting a Form with Server Actions
javascript
// 1. Define the Server Action
// This function runs EXCLUSIVELY on the secure backend server.
async function updateUser(formData) {
  "use server"; // This directive marks it as an exposed endpoint
  
  const username = formData.get('username');
  // Direct database mutation! No API routes required.
  await db.user.update({ name: username });
}

// 2. The UI Component (Can be Server OR Client component)
export default function ProfileForm() {
  return (
    // 3. We pass the function reference directly to the HTML action attribute!
    <form action={updateUser}>
      <input type="text" name="username" placeholder="New name" />
      <button type="submit">Save</button>
    </form>
  );
}

Common Pitfalls

  • Security and Validation: Because a Server Action is an exposed backend endpoint (React generates a hidden URL for it under the hood), malicious users can theoretically hit it directly. You MUST validate user authorization and sanitize the input data (using Zod) inside the Server Action before touching your database.

Interview Questions

What is Progressive Enhancement and how do Server Actions support it?

Progressive Enhancement means an application should still fundamentally work even if JavaScript fails to load or is disabled in the browser. Because Server Actions are attached directly to the native <form action={...}> attribute, the browser can natively submit the form via standard HTTP POST request without requiring any client-side JavaScript.

How do you trigger a Server Action outside of a <form> element (e.g., clicking a 'Like' button)?

While Server Actions are designed for forms, you can invoke them anywhere by wrapping them in the startTransition API or directly importing and calling them in an onClick handler of a Client Component.

Real-World Example

Mutating Data and Revalidating the Cache: The combination of Server Actions and revalidatePath allows you to build completely dynamic, real-time database applications without writing a single useState, useEffect, or fetch API call.

example
javascript
import { revalidatePath } from 'next/cache';

// action.js
export async function addComment(formData) {
  "use server";
  
  const text = formData.get('comment');
  await db.comments.create({ text });
  
  // This is the magic of Next.js Server Actions.
  // We tell the server: "The database changed. Purge the cache for this URL,
  // re-run the Server Components, and instantly push the fresh HTML to the browser!"
  revalidatePath('/blog/post-1');
}

// page.js
export default function CommentSection() {
  return (
    <form action={addComment}>
      <textarea name="comment"></textarea>
      <button type="submit">Post Comment</button>
    </form>
  );
}

Check Your Knowledge

Test your understanding of Server Actions with these quick questions.

Question 1

What directive must be placed at the top of a function to designate it as a Server Action?

Question 2

Which native HTML attribute is best practice to attach a Server Action to?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Server Actions

Overview

If Server Components are the modern way to read data from the backend, Server Actions are the modern way to write data to the backend (e.g., submitting forms, updating databases).

Historically, to handle a form submission in React, you had to: 1. Create a useState controlled form. 2. Write a separate Express.js or Next.js API Route (e.g., /api/submit). 3. Use fetch() in the component to send a JSON POST request to that URL.

Server Actions eliminate this entire process. A Server Action is literally an asynchronous JavaScript function defined with the `"use server"` directive. You can pass this function directly to the action attribute of an HTML <form>. When the user clicks submit, React automatically encrypts the form data, bridges the network gap, and executes your backend function directly on the server.

Syntax

Submitting a Form with Server Actions
javascript
// 1. Define the Server Action
// This function runs EXCLUSIVELY on the secure backend server.
async function updateUser(formData) {
  "use server"; // This directive marks it as an exposed endpoint
  
  const username = formData.get('username');
  // Direct database mutation! No API routes required.
  await db.user.update({ name: username });
}

// 2. The UI Component (Can be Server OR Client component)
export default function ProfileForm() {
  return (
    // 3. We pass the function reference directly to the HTML action attribute!
    <form action={updateUser}>
      <input type="text" name="username" placeholder="New name" />
      <button type="submit">Save</button>
    </form>
  );
}

Common Pitfalls

  • Security and Validation: Because a Server Action is an exposed backend endpoint (React generates a hidden URL for it under the hood), malicious users can theoretically hit it directly. You MUST validate user authorization and sanitize the input data (using Zod) inside the Server Action before touching your database.

Interview Questions

What is Progressive Enhancement and how do Server Actions support it?

Progressive Enhancement means an application should still fundamentally work even if JavaScript fails to load or is disabled in the browser. Because Server Actions are attached directly to the native <form action={...}> attribute, the browser can natively submit the form via standard HTTP POST request without requiring any client-side JavaScript.

How do you trigger a Server Action outside of a <form> element (e.g., clicking a 'Like' button)?

While Server Actions are designed for forms, you can invoke them anywhere by wrapping them in the startTransition API or directly importing and calling them in an onClick handler of a Client Component.

Real-World Example

Mutating Data and Revalidating the Cache: The combination of Server Actions and revalidatePath allows you to build completely dynamic, real-time database applications without writing a single useState, useEffect, or fetch API call.

example
javascript
import { revalidatePath } from 'next/cache';

// action.js
export async function addComment(formData) {
  "use server";
  
  const text = formData.get('comment');
  await db.comments.create({ text });
  
  // This is the magic of Next.js Server Actions.
  // We tell the server: "The database changed. Purge the cache for this URL,
  // re-run the Server Components, and instantly push the fresh HTML to the browser!"
  revalidatePath('/blog/post-1');
}

// page.js
export default function CommentSection() {
  return (
    <form action={addComment}>
      <textarea name="comment"></textarea>
      <button type="submit">Post Comment</button>
    </form>
  );
}

Check Your Knowledge

Test your understanding of Server Actions with these quick questions.

Question 1

What directive must be placed at the top of a function to designate it as a Server Action?

Question 2

Which native HTML attribute is best practice to attach a Server Action to?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A