How to use server actions in Next.js
Offloading work from your client to your server is easy with Next.js server actions . Here's everything you need to know about server actions in Next.js.
What is Server Action?
Server Actions or server actions allow you to write one-off server-side functionality right alongside your server components. This is important because you no longer need to write API routes when submitting forms or making any other type of data changes, including GraphQL data changes.
You can write functions that run on the server and then call them from client or server components. This is an alpha feature in Next.js 13.4, built on top of React Actions. Using server actions results in reduced client-side JavaScript and can help you gradually create advanced forms.
Example of server action
With server action, you can make changes inside Next.js, on the server. Let's look at this new feature with an example page created with Next.js that displays a form that allows you to create posts.
These are the imports:
import Link from "next/link" import FormGroup from "@/components/FormGroup" import { revalidateTag } from "next/cache" import { redirect } from "next/navigation"
Now with the post creation code. This function is a server action. It runs on the server and sends the post title and content to the API (creates the post in the database):
async function createPost(data) { "use server" const title = data.get("title") const body = data.get("body") await fetch("http://127.0.0.1/posts", { header: {"Content-Type": "application/json"}, method: POST, body: JSON.stringify({title, body}) }) revalidateTag("posts") redirect("/") }
This function takes the post title and content, then sends it to the /posts endpoint via a POST request. It then forces the cache to refresh the content associated with the "post" tag and redirects back to the home page.
Here is the form that collects new post titles & content:
export default NewPostForm() { return ( form action={createPost} div FormGroup label htmlFor="title" Title label input type="text" name="title" id="title" FormGroup div div FormGroup label htmlFor="title"Bodylabel textarea type="text" name="body" id="body" textarea FormGroup div div button Save button div form ) }
You can see that the form contains no logic related to creating a post, just a form action: the createPost() function . Recall that the createPost function has a "use server" directive declaring that everything in that function will run on the server.
All the code is running on the server and your client knows nothing about it. This is because the form is a server component and nothing is dynamically displayed on the client.
When the Save button is clicked , Next.js will call the createPost() function . This sends the title and body as form data. It will be posted to the local API to save the information.
Verify the post again
At the bottom of the createPost() function is the following line of code:
revalidateTags("posts")
To understand what the function means, imagine that you have a page of posts. Inside the posts component, you'll call a function called getPosts() to get all the posts from the database and display them for the user to see:
export default async function Posts(){ const posts = await getPosts() return ( div {posts.map(post => { PostCard key={post.id} {.post} })} div ) }
The getPosts() function looks like this:
async function getPosts() { const res = await fetch("https://127.0.0.1/posts?sort=title", { next: {tags: ["posts"], revalidate: 3600 } }) return res.json() }
This function passes the next option to fetch, allowing you to set the revalidation interval. By default, every single fetch request you make inside the server component will be cached permanently. Monitoring the cache and refreshing it when necessary is an important part of the data fetching process in Next.js.
The above code tells Next.js to store post data for up to one hour (3,600 seconds). After an hour, that data becomes stale and Next.js "refreshes" it to get the latest data from the database.
Remember that the createPost() function calls revalidateTag("posts") after it has completed the remaining work. This forces Next.js to re-fetch data including the new post the app just created.
To make sure all the code is running on the server, you can add the following console log command in the createPost() function :
console.log("Running on the server")
Then try creating a new post by clicking the submit button. If your code is running on the server, that log message will show up on your terminal. But if it is running on the client then the log will show up in the browser console.
Above is how to use server actions in Next.JS. Hope the article is useful to you.
You should read it
- Download the $ 14 action game Axiom Verge, which is free
- 19 free Photoshop Action download sites
- Why use Windows 10 Action Center instead of Settings app?
- Network basics: Part 3 - DNS Server
- Action buttons in PowerPoint 2016
- This is how to customize and disable (turn off) Action Center on Windows 10
- How to edit the Action Center quick button on Windows 10 19H1
- 7 great ideas using Raspberry Pi as a server
May be interested
- How to set up your own Git server on Linuxwhile you can count on globally renowned git hosting services like github, in some cases it is better to host a personal git server for enhanced privacy, customizability, and security.
- Use the action buttons on Slide in PowerPointintroduce in detail how to use the action buttons on the slide in powerpoint. step 1: go to insert - shape - move to action buttons - select the action button to use.
- How to edit the Action Center button in Windows 10on the latest update, users can edit the action center button in windows 10, reset the features available on the action center and arrange it in the direction that suits the work for you.
- Use IIS to set up FTP Server on Windowsset up an ftp server (file transfer protocol server) to share and convert large files with unlimited traffic.
- How to change DNS server on the most popular routerschanging the dns server settings on your router is not difficult, but every manufacturer uses their own custom interface, which means the process can be very different depending on which router you are owned.
- What is VPS? VPS used to do? What is VPS different from Server?what is vps? vps used to do? what is vps different from server ?. when you intend to learn about network data or open the website, you will definitely be introduced to many different server and server services. but server hosting has a lot of tricks
- How to create notes on Action Center for Windows 10action note is an application installed on windows 10, enabling users to create notes right on the action center interface. after that, we can pin these notes to start mennu easily.
- 7 great ideas using Raspberry Pi as a serverraspberry pi is a great solution for many computer projects, from learning programming to remote control a car to building a basic stop-motion animation studio. but do you know that raspberry pi can also be used as a server? here are some ideas for using raspberry pi as a server.
- Download Aegis Defenders, a super cool action game, for freeaegis defenders has colorful 2d graphics with unique gameplay, mixing tower defense and metroidvania with 2d action scenes to create challenging levels.
- How to edit and reset Windows 11 Action Centerusers can change and edit settings in action center to suit their needs. if you don't see the edit icon, you should reset windows 11 action center.