A Server Action in Next.js 14 is an asynchronous function that executes directly on the server whenever a form is submitted. This feature allows you to handle server-side logic seamlessly, improving performance and security. In this guide, we’ll explore how to effectively implement Server Actions in Next.js 14 to optimize your application's server-side operations.

Next.js 14 introduces several powerful features that streamline development, including:

  • App Router
  • Server Actions
  • Route Handlers
  • Client and Server Components

In this article, we’ll dive deep into Server Actions in Next.js 14, exploring how they can enhance your development process.

What are Server Actions in Next.js 14?

A Server Action in Next.js 14 is an asynchronous function executed directly on the server whenever a form is submitted. It enables you to execute server-side code seamlessly, eliminating the need for separate API endpoints. This way, you don't have to make a separate backend or API and don't need to send requests to the API. You can communicate with a database directly in a Server Action.

You can use it in both client and server components.

Using Server Actions Next.js 14

Using Server Actions in Server Components

Create an asynchronous function within a server component to leverage Server Actions in Next.js 14. Add the "use server" directive inside the function (at the top). Then attach an action property to the form element.

The Server Action receives a formData object as an argument that lets you access the values of the input fields. After this, you can perform validation and store information directly in a database. No need to create an API endpoint.

// server component

export const Form = () => {
  const createPost = async (formData) => {
    "use server"
    const title = formData.get("title")
    const description = formData.get("description")

    // store the post in the database directly
  }

  return (
    <form action={createPost}>
      <input type="text" name="title" />
      <input type="text" name="description" />
      <button type="submit">Submit</button>
    </form>
  )
}

Using Server Actions in Client Components

Because client components are rendered on the client side, Server Actions in Next.js 14 cannot be created directly within them. But what you can do is, you can create a new file and add the use server directive at the top of the file. Now any function you create inside of that file will be considered a Server Action. Then you can import those Server Actions into a client component.

"use server"

export const createPost = async (formData) => {
  const title = formData.get("title")
  const description = formData.get("description")

  // store the post in the database directly
}

Now you can import this Server Action in a client component.

// client component
"use client"

import { createPost } from './actions'

export const Form = () => {
  return (
    <form action={createPost}>
      <input type="text" name="title" />
      <input type="text" name="description" />
      <button type="submit">Submit</button>
    </form>
  )
}

Showing a Loading State

Now you might be wondering, how can we show a loading state because the function is being executed on the server.

To show a loading state in your Next.js 14 Server Actions, create a separate client component for your button. Inside of this component, you can use the useFormStatus hook. It tells you whether the Server Action has finished executing or is still being executed.

Note: You can only use the useFormStatus hook inside of a form. That's why you have to create a separate component for your button and place it inside the form.

"use client"

import { useFormStatus } from "react-dom"

export const Button = ({ children }) => {
  const { pending } = useFormStatus()

  return (
    <button type="submit" disabled={pending}>
      {children} {pending && "Loading..."}
    </button>
  )
}

Now we can use it inside the form.

// client component
"use client"

import { createPost } from './actions'
import { Button } from './Button'

export const Form = () => {
  return (
    <form action={createPost}>
      <input type="text" name="title" />
      <input type="text" name="description" />
      <Button>Submit</Button>
    </form>
  )
}

Next JS Server Action Error Handling

To manage errors and success messages with Next.js 14 Server Actions, utilize the useFormState hook. It accepts a Server Action and an Initial State as an argument. It returns the New State and a copy of the Server action.

// client component
"use client"

import { createPost } from './actions'
import { Button } from './Button'
import { useFormState } from "react-dom"
import { useEffect } from 'react'

export const Form = () => {
  const [createPostState, createPostAction] = useFormState(createPost, {
    error: null,
    success: false
  })

  useEffect(() => {
    if (createPostState.success) {
      alert("Post created!")
    }

    if (createPostState.error) {
      alert(createPostState.error)
    }
  }, [createPostState])

  return (
    <form action={createPostAction}>
      <input type="text" name="title" />
      <input type="text" name="description" />
      <Button>Submit</Button>
    </form>
  )
}

Server Action Success State

When using the useFormState hook with Next.js 14 Server Actions, your Server Action will receive an additional argument prevState. So you can modify your server action like this:

"use server"

export const createPost = async (prevState, formData) => {
  const title = formData.get("title")
  const description = formData.get("description")

  if (!title) {
    return { error: "Enter the title!", success: false }
  }

  if (!description) {
    return { error: "Enter the description!", success: false }
  }

  // store the post in the database directly
  return { error: null, success: true }
}

Conclusion

Server Actions in Next.js 14 is an amazing feature for web development. It makes development faster since you don't need a separate backend or API. From creating Server Actions to using them in different scenarios, this guide has provided a comprehensive overview of using Next.Js 14 Server Actions. To learn more about Next.Js 14 and Server Actions, read their official documentation:


Frequently Asked Questions

1. What are Server Actions in Next.js 14?

Answer: Server Actions in Next.js 14 are asynchronous functions that run directly on the server whenever a form is submitted. This feature eliminates the need for separate API endpoints, allowing for more streamlined and secure server-side logic.

2. How do Server Actions in Next.js 14 improve performance?

Answer: Server Actions in Next.js 14 improve performance by executing code on the server, reducing the need for client-side API calls. This results in faster response times and more efficient handling of server-side logic.

3. Can I use Server Actions in both client and server components in Next.js 14?

Answer: Server Actions can only be defined in server components in Next.js 14. However, they can be utilized within client components by importing and calling these server-defined actions.

4. How do I handle loading states with Server Actions in Next.js 14?

Answer: To manage loading states when using Server Actions in Next.js 14, you can create a separate client component for your button and use the useFormStatus hook to check whether the action is still being executed.

5. How can I implement error handling in Next.js 14 Server Actions?

Answer: Error handling in Next.js 14 Server Actions can be implemented using the useFormState hook. This hook allows you to manage the state of your Server Actions, providing a way to handle and display errors or success messages to the user.


🚨 Do you need a Portfolio Website? 🚨

With MyDevPage you can build your own portfolio website in 1 minute. You need to focus on building great projects and enhancing your skills rather than wasting your time in building and designing a portfolio website from scratch.

MyDevPage handles everything:

  • Update easily on the go from your phone
  • Beautiful Portfolio Website
  • Upload your resume easily
  • Useful Website Analytics
  • Simple Customization
  • Add Custom Domain
  • Control over SEO
  • Contact Form

Try it out today (it's Free!) 👉 MyDevPage 👈

MyDevPa.ge