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 | Concept | Meaning | |---|---| | `"use server"` | Directive that marks an async function as server-only. | | Mutation | Operation that changes data. | | `FormData` | Standard object for submitted form fields. | | `revalidatePath` | Refreshes cached data for a path after mutation. | | Progressive enhancement | Forms 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 | Mistake | Why It Happens | Correct Approach | |---|---|---| | Trusting form input | The action runs on the server but input is still user-controlled. | Validate and authorize every mutation. | | Forgetting cache revalidation | UI may show stale cached data. | Use `revalidatePath` or tag-based invalidation. | | Using actions for external webhooks | Actions 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 | Feature | Browser Impact | Notes | |---|---|---| | HTML forms | Broad support | Server Actions integrate with form submissions. | | Client invocation | Requires React/Next runtime | Used for interactive flows. | | Server mutation | Server-side | Keeps 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 | Need | Server Action? | |---|---| | In-app form submit | Yes | | Stripe webhook | No | | Save profile settings | Yes | | Public mobile API | No | | Revalidate after mutation | Yes | ## 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.