Member-only story

NextJs Server Actions: Behind the Scenes you might need to know

Bhavya Dhiman
3 min readAug 14, 2024

--

NextJs Sever Actions

If you are not a medium member, click on this link: https://medium.com/@bhavyadhiman7/nextjs-server-actions-behind-the-scenes-you-might-need-to-know-32bdf894cb3b?sk=2edee18b03a3c685e5c94c10d5aa798d

Since v13.4, NextJs introduced Server Actions, in which you can call `async` functions directly without any need to call a REST API even in the client component. But do you know behind the scenes what is even happening. Let me tell you by showing an example.

In the page.tsx compoent inside app folder, let’s modify a component (client component due to interactivity):

'use client';
import { serverAction1, serverAction2 } from "./actions";

export default function Home() {

return (
<div>
<button className="btn1" onClick={() => serverAction1()}>Inspect Server Action 1</button>
<button className="btn2" onClick={() => serverAction2()}>Inspect Server Action 2</button>
</div>
);
}

For actions, create an actions/index.ts file inside an app folder and let’s create two functions inside the same file:

export const serverAction1 = async () => {
console.log('SERVER ACTION CALLED 1!');
}


export const serverAction2 = async () => {
console.log('SERVER ACTION CALLED 2!');
}

--

--

No responses yet