Next.js Server Actions: Challenges and Solutions

Jul 4, 2024

Next.js Server Actions: Challenges and Solutions

Overview

  • Server actions help handle form submissions without separate API endpoints.
  • Combines server-side logic with React components.
  • Provides flexibility in organizing backend and frontend code.

Creating Server Actions

  • Can be defined directly inside React components or in separate files.
  • Use the use server directive to annotate functions meant to run on the server.
  • Actions can be imported into client or server components.

Application Example

  • Platform: Deals Ford Dev (dealsfordev.com).
  • Allows users to submit deals which are saved to a Zeta database.
  • Admin dashboard for approving/rejecting submitted deals.

Problem: Duplicate Submissions

  • Users clicking the submit button multiple times due to lack of feedback.
  • Resulted in duplicate entries and poor user experience.

Solution Steps

  1. Detecting the Issue: Using Sentry

    • Integrated Sentry to track errors and alerting.
    • Identified dead clicks in the Sentry dashboard.
  2. Displaying Loading State

    • Followed Next.js documentation to use useFormStatus hook.
    • Converted form to a client component and used pending state to disable the submit button and show a loading text.
    • Initial attempt failed as the approach was incorrect.
  3. Fixing the Implementation

    • Realized useFormStatus hook must be used as a child of the form element using a server action.
    • Moved the submit button logic into its own client component.
    • Kept the form as a server component.

Recommendations

  1. Separate Actions Directory

    • Create a directory to host all server actions for clean code separation.
  2. Types Directory

    • Store shared enums, types, etc., in a separate directory.
    • Ensure both server and client sides can access these without import errors.
  3. Form Validation with Zod

    • Define schema with Zod for server-side data validation.
    • Parse incoming data and catch errors for user feedback.
  4. Redirect After Submission

    • Redirect users to a new page after successful form submission.
    • Example: Navigate to a sample page and provide navigation back to the form.

Future Directions

  • Continues to build with server actions in Next.js and work on areas of improvement.
  • Plans to create a course covering all learned concepts including Next.js, server components, actions, and third-party integrations.

Additional Tips

  • Check the Next.js documentation frequently for updates and clarifications.
  • Use tools like Sentry for error tracking and improving user experience.