ReviseAlgo Logo

Data Fetching

Server Actions

Learn Server Actions in Next.js for form submissions, mutations, cache invalidation, and server-side business logic.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Define a Server Action with "use server".
  • Use actions for form submissions and mutations.
  • Revalidate paths after data changes.
  • Decide when a Route Handler is a better fit.
  • Difficulty: Intermediate.

    2. Prerequisites

  • Server Components.
  • Forms and HTTP basics.
  • Route Handlers.
  • 3. Overview

    Server Actions are async server functions that can be invoked from forms or Client Components. They let you run mutations on the server without manually creating a separate API endpoint for every in-app action.

    4. Why This Topic Matters

    Applications need mutations: creating posts, saving settings, deleting records, and updating profiles. Server Actions keep those mutations close to the UI while still running securely on the server.

    5. Real-World Analogy

    A Server Action is like handing a completed form to a staff member behind the counter. The user interacts with the form, but the actual record update happens in the secure back office.

    6. Core Concepts

    ConceptMeaning
    "use server"Directive that marks an async function as server-only.
    MutationOperation that changes data.
    FormDataStandard object for submitted form fields.
    revalidatePathRefreshes cached data for a path after mutation.
    Progressive enhancementForms can submit without custom client fetch code.

    7. Syntax & API Reference

    8. Visual Diagram

    9. Live Example - Full Working Code

    What just happened? The form submits to a server function that validates, mutates data, and refreshes the todos route.

    10. Interactive Playground

    Try this:

  • Add a form that calls a Server Action.
  • Validate empty input.
  • Call revalidatePath() after saving data.
  • 11. Common Mistakes

    MistakeWhy It HappensCorrect Approach
    Trusting form inputThe action runs on the server but input is still user-controlled.Validate and authorize every mutation.
    Forgetting cache revalidationUI may show stale cached data.Use revalidatePath or tag-based invalidation.
    Using actions for external webhooksActions are app mutation functions.Use Route Handlers for external HTTP calls.

    12. Best Practices

  • Use Server Actions for in-app mutations.
  • Validate input with a schema or explicit checks.
  • Re-check authorization inside the action.
  • Revalidate affected paths or tags after writes.
  • Keep action logic focused and call shared service functions for business rules.
  • 13. Browser Compatibility

    FeatureBrowser ImpactNotes
    HTML formsBroad supportServer Actions integrate with form submissions.
    Client invocationRequires React/Next runtimeUsed for interactive flows.
    Server mutationServer-sideKeeps secrets out of browser.

    14. Interview Questions

    Easy: What directive marks a Server Action?

    Answer: "use server".

    Medium: What are Server Actions best for?

    Answer: In-app mutations such as form submissions, settings updates, and data writes.

    Hard: Why still validate authorization in a Server Action?

    Answer: Server Actions can mutate protected data, so the server must verify the current user is allowed to perform the operation.

    15. Debugging Exercise

    Bug report: "The record saves, but the page still shows the old list."

    Solution

    The mutation likely did not revalidate cached data. Call revalidatePath('/affected-route') or use tag-based invalidation after the write.

    16. Practice Exercises

  • Easy: Create a contact form Server Action.
  • Medium: Add validation and error handling.
  • Hard: Save data, revalidate a list page, and redirect after success.
  • 17. Scenario-Based Challenge

    A settings form updates the user's display name. Should you use a Server Action or a Route Handler?

    Walkthrough

    Use a Server Action if the mutation is only used inside the Next.js app. Validate the session and input, update the database, then revalidate affected UI.

    18. Quick Quiz

    1. Are Server Actions async? Answer: Yes. 2. What object contains form fields? Answer: FormData. 3. What refreshes cached route data? Answer: revalidatePath. 4. Are Server Actions for public webhooks? Answer: Usually no. 5. Should input be validated? Answer: Always.

    19. Summary & Key Takeaways

  • Server Actions run mutations on the server.
  • They can be used directly with forms.
  • Validate input and authorization.
  • Revalidate cached UI after writes.
  • Use Route Handlers for external HTTP endpoints.
  • 20. Cheat Sheet

    NeedServer Action?
    In-app form submitYes
    Stripe webhookNo
    Save profile settingsYes
    Public mobile APINo
    Revalidate after mutationYes

    21. Further Reading

  • Next.js Docs: Server Actions and Mutations.
  • Next.js Docs: Revalidating.
  • React Docs: Forms.
  • 22. Next Lesson Preview

    Next, you will learn API Routes and how they relate to App Router Route Handlers.