Getting Started with Next.js Server Actions
9 June, 2023
3
3
0
Contributors
In Next.js 13, a fresh feature called Next.js Server Actions was introduced. This feature is designed to enable you to execute server code without the hassle of creating a separate API endpoint.
This article will walk you through the process of utilizing Next.js Server Actions, providing a comprehensive understanding of how to incorporate them into your projects.
Let's dive in and explore the world of Next.js Server Actions together.
What is the purpose of Next.js Server Actions?
Server Actions, as the name suggests, are essentially functions executed on the server but can be invoked from the client, just like any regular function.
This feature represents a significant advancement for Next.js since it eliminates the need to create a separate API endpoint in order to run server-side code. For Next.js developers, this introduces an entirely new developer experience that has the potential to revolutionize their workflow.
To be completely transparent, it's important to note that Server Actions are not exclusive to Next.js. In fact, they are a built-in functionality of React.js, although it's worth mentioning that this functionality is still in the alpha stage of development.
What are the potential uses of Next.js Server Actions?
Server Actions are an incredibly powerful feature that offers a wide range of applications.
Let me provide you with a few examples:
- Writing to a database: Instead of creating an API endpoint, you can directly write data to a database from the client. By defining your logic within a server action, this process becomes seamless.
- Server logic: Perform various server-related tasks using server actions. For instance, you can effortlessly send emails, create files, or execute other business logic that typically resides on the server.
- Calling external APIs: Server actions enable you to make direct calls to external APIs without the need for setting up a dedicated API endpoint. This streamlines the process and saves valuable development time.
Benefits of Next.js Server Actions
Using Next.js Server Actions offers several advantages:
- No API endpoint creation: With Next.js Server Actions, you can execute server code without the hassle of creating an API endpoint. This simplifies the development process and saves time.
- Easy navigation to action definitions: In your code editor, you can conveniently navigate to the definition of a server action by simply clicking on it. This eliminates the need to manually search for the corresponding code within your project.
- Type safety: By utilizing TypeScript, you can define the arguments and return value of your server actions. Next.js will automatically validate these types, ensuring a higher degree of reliability and reducing potential runtime errors.
- Concise code: Next.js Server Actions allow you to write less code compared to traditional approaches. The process involves defining a function and its parameters, which significantly reduces the amount of boilerplate code. Consequently, you can call these actions from the client side with ease.
Next.js Server Actions offer a multitude of benefits, and you'll likely discover various use cases where they prove invaluable.
Define a Server Action in Next.js
To define a Next.js Server Action, you can typically do it in any of your components, but there are a few exceptions to keep in mind. Let's explore a few scenarios.
Before you begin, make sure you have enabled the experimental server actions in your next.config.js
file:
module.exports = {
experimental: {
serverActions: true,
}
};
That way, you'll have the necessary setup to work with server actions in Next.js.
Creating a Server Action within a Server Component
When defining a server action within a server component, all you have to do is create a function and include the use server
directive at the beginning.
Here's an example of a valid server action:
async function myActionFunction() {
'use server';
// Perform some tasks
}
It's crucial to note that server action functions must have arguments and return values that can be serialized according to the React Server Components protocol. This is necessary because the function's response will be serialized and transmitted to the client.
Describing numerous Next.js Server Actions
Instead of defining a server action in a conventional manner, there's an alternative approach. You can export multiple functions from a file and include the use server
directive at the top of the file.
For example:
'use server'
export async function myActionFunction() {
// Perform some task
}
export async function anotherActionFunction() {
// Perform another task
}
It's important to note that client components are only able to import actions from server action files. They cannot define server actions directly within the same file. However, you can still import them from a file that defines multiple server actions using the use server
directive.
Steps to Trigger a Next.js Server Action
There are several options available to trigger a server action.
Triggering a Server Action via a Form
If you want to invoke a server action from a form, the easiest approach is to do it through the form itself. You can achieve this by using the onSubmit
property of the form
element and calling the server action from there.
Here's an example of how you can implement it:
export function MyFormComponent() {
function handleFormAction(formData) {
// Use server action here
'use server';
const name = formData.get('name');
// Do something with the form data
}
return (
<form onSubmit={handleFormAction}>
<input type="text" name="name" />
<button type="submit">Save</button>
</form>
);
}
Triggering a Server Action with a Button
You can also trigger a server action by clicking a button. To achieve this, you can utilize the handleAction
property of the button element and invoke the server action from within it.
In the code example below, we have a Form component. Inside this component, there is an asynchronous function called handleSubmit
. Within this function, we perform some operations related to the server action.
export function Form() {
async function handleSubmit() {
'use server';
// Perform server-related operations here
}
return (
<form>
<input type="text" name="name" />
<button formAction={handleSubmit}>Submit</button>
</form>
);
}
Executing a Server Action directly
You can also trigger a server action directly by using the useTransition
hook. To begin, we create a separate file that contains various server actions:
'use server';
export async function saveData(id) {
await addItemToDb(id);
revalidatePath('/product/[id]');
}
Next, in our client component, we import the server action and use the useTransition
hook to invoke it imperatively:
'use client';
import { useTransition } from 'react';
import { saveData } from '../actions';
function ClientComponent({ id }) {
const [isPending, startTransition] = useTransition();
return (
<button onClick={() => startTransition(() => saveData(id))}>
Save
</button>
);
}
Performing data revalidation following a Server Action
To revalidate the data for a particular path, you can utilize the revalidatePath
function. This can come in handy when you need to validate the data for a specific path following the execution of a server action.
Progressive Enhancement
When you utilize Server Actions through a form
component, they remain functional even when JavaScript is disabled. This is because the form is submitted to the server, unlike imperatively invoked actions that only function with JavaScript enabled.
If possible, it is recommended to utilize Server Actions from forms to guarantee the proper functioning of your application, even in cases where JavaScript is disabled.
Server Mutations
In Next.js, Server Mutations are referred to as Server Actions. These actions allow you to modify your data and invoke functions like redirect
, revalidatePath
, or revalidateTag
.
If you don't need to perform any of these actions, then you're not actually performing a mutation. In such cases, you can simply call the server action directly from your client components without the need for using useTransition
.
Is Next.js Server Actions the Next Big thing?
In this article, we have discussed the usage of Next.js Server Actions and how they can be called from client components.
Although these features are currently available for use, it's important to exercise caution as they are still in the experimental stage. Keep in mind that the API might undergo changes in the future.
showwcase
blogathon
growincommunity