How to use Server Actions with NextJS
Nowadays, performance and efficiency have become major concerns. Users are increasingly demanding about their experience when spending time on a website.
To further optimize page load performance, we now have a magical feature: Server Actions.
Server Actions were introduced in Next.js 13 but became truly usable starting with Next.js 14.
They allow data management directly on the server, while simplifying client-side page loading.
If you're a beginner, it is essential to follow a comprehensive React course before using Next.js. A good Next.js developer is, above all, a good React developer (who is, in turn, a good JavaScript developer)! 😋
Understanding Server Actions
Server Actions, as mentioned, are one of Next.js's flagship features. They enable executing instructions on the server directly from components (even Client Components).
A Client Component, simply put, is code that runs in the user's browser. By contrast, a Server Component is executed on the server and sent pre-rendered to the user.
Unlike methods like getServerSideProps
or getStaticProps
(deprecated as of Next.js 13), Server Actions integrate directly into components without requiring dedicated pages or complex hooks.
Why Use Server Actions?
Using Server Actions offers several benefits:
- Improved Performance: By executing code directly on the server, client-side load is reduced, significantly improving load times.
- Simplified Code: Server Actions eliminate the need to create separate API files or use functions like
getServerSideProps
. Everything can now be managed within the components themselves. - Reduced Client-Side JavaScript: Since most of the work is done server-side, the size of the JavaScript bundle sent to the client is smaller, speeding up the application.
Setting Up Server Actions in Next.js
Initializing a Next.js Project
If you're new to Next.js, here’s how to initialize a project:
npx create-next-app@latest
During initialization, you can choose between the app or pages router. Choose the app router. It’s the latest router offered by Next.js, enabling better application structure and full use of Server Components and Server Actions.
Configuring Server Actions
Server Actions are used directly within components. Simply mark a function with the async
attribute to use it as a Server Action.
Example: In a Server Component
Server Components can use:
- Inline functions
- Modules with "use server"
Here’s an example using an inline function:
export default function Page() {
// ...
// Server Action
async function create() {
"use server";
const res = await fetch('https://believemy.com');
// ...
}
return (
);
}
In this example, we dynamically fetch data for an article. This approach greatly simplifies data flow while reducing the amount of client-side code executed.
Example: Using Modules
For modular use, create a new file and include the use server
directive. All functions in this file are treated as Server Actions.
'use server';
export async function create() {
// ...
}
export async function replace() {
// ...
}
To use the Server Action, include the following in a Server Component:
import { create } from "./actions";
export default function ServerComponent() {
return;
}
The action
attribute informs Next.js to use a Server Action. It sends all form data to the server when the user submits the form.
Example: In a Client Component
Client Components can only use modules for Server Actions. Using the previous actions.jsx
example:
'use client';
import { create } from "./actions";
export default function ClientComponent() {
return;
}
API Routes vs. Server Actions
With the advent of Server Actions, many developers wonder if API Routes are still necessary.
API Routes, introduced in earlier Next.js versions, create dedicated endpoints for APIs, used throughout a project to communicate with the server. 👀
With Server Actions, these dedicated routes are mostly unnecessary, as you can handle requests directly in components.
Here’s a summary:
When to Use API Routes:
- When you need to expose API endpoints for external services.
- To centralize server logic in a single file.
When to Use Server Actions:
- When data retrieval is directly tied to component rendering.
- To optimize performance and simplify code by avoiding additional client API requests.
Another advantage of Server Actions is caching. Requests to fetch the latest articles on your site, for instance, can be cached to avoid repeated executions, significantly improving load times, especially for infrequently updated data.
FAQ on Server Actions
Our learners often ask questions about Server Actions. Here’s a quick summary of the most insightful ones:
What are best practices for using Server Actions in Next.js?
Ensure proper server-side error handling and only use Server Actions when truly necessary. Otherwise, they can add unnecessary complexity to your code.
Do Server Actions affect SEO?
No, they even improve SEO by speeding up page rendering.
Can I use external APIs with Server Actions?
Yes, Server Actions are great for interacting with external APIs. It also ensures API keys stay secure!
Are API Routes still useful in Next.js 14 and beyond?
Yes, for cases where you need to expose an API to external services. However, Server Actions suffice for most use cases.
How can I learn Next.js?
With our course! 😇 You can find it here.