Server Actions in Next.js

NextJS is a React framework that is used to build full-stack web applications. Server actions in Next.js refer to the functionalities and processes that occur on the server side of a Next.js application. In this article, we will learn about Server Actions in Next.js with Examples.

What is Server Action in Next.js

Server Action is an Asynchronous server function that can be used on the server side as well as the client side. It is used to handle operations related to the server, such as Form Submissions, Data Updating ( mutations ), Authentication, and Background Tasks such as Email Sending, etc.

To define a Component as a server, You can use a “use server”; directive at the top of an async function or top of the separate file to mark the function as a Server Action.

If you are using Server Action in a client component then you have to make a separate file for the server action and put it in the client component to use that server action.

Syntax:

'use server'

export async function formSubmit() {
//other code
}

If you are using Server Action in a server component then you directly define the server action in your component function and use that.

Syntax:

// Server Component
export default function Page() {

// Server Action
async function formSubmit() {
'use server'

//Server Action Logic
}

return (
//component element
)
}

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command and answer a few questions.

npx create-next-app@latest app_name

Step 2: It will ask you some questions, so choose as the following.

√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

Step 3: After creating your project folder, move to it using the following command.

cd app_name

Project Structure:

Project Structure

Example: The below example demonstrate the implementation of server action in next.js

In this example, we are saving the form data into a data.json file. We can also use server action in a Form Action Attribute. Note: Remove the include css file from layout.js

JavaScript
//File path: src/app/page.js

'use client';
import formSubmit from './formSubmitServerAction.js'
import formData from '../../data.json'

export default function Page() {

    return (
        <div style={{ display: 'flex', gap: "3%", margin: "10px" }}>
            <form action={(e) => formSubmit(e)}>
                <label>Name</label>
                <input type="text"
                    placeholder="Enter Your Name"
                    name="name" required />
                <br />
                <label>Age</label>
                <input type="text"
                    placeholder="Enter Your Age"
                    name="age" required />
                <br />
                <label>City</label>
                <input type="text"
                    placeholder="Enter Your City"
                    name="city" required />
                <br />
                <button type="submit">Submit</button>
            </form>

            <br /><br />
            <table border={2} cellPadding={10}>
                <thead>
                    <tr>
                        <td>Name</td>
                        <td>Age</td>
                        <td>City</td>
                    </tr>
                </thead>
                <tbody>
                    {
                        formData.map((item, key) => {
                            return (
                                <tr key={key}>
                                    <td>{item.name}</td>
                                    <td>{item.age}</td>
                                    <td>{item.city}</td>
                                </tr>
                            )
                        })
                    }
                </tbody>
            </table>
        </div>
    );
}
JavaScript
//File path: src/app/formSubmitServerAction.js

'use server'
import fs from 'fs';
import formData from '../../data.json'

const formSubmit = async (e) => {
    const name = e.get('name')
    const age = e.get('age')
    const city = e.get('city')

    formData.push({ name, age, city })
    fs.writeFileSync('data.json', JSON.stringify(formData, null, 4))
}

export default formSubmit;
JavaScript
//File path: ./data.json (root) (Remove this comment while implementing) 

[  ]

Start your application using the command:

npm run dev

Output: Open http://localhost:3000 to view the output.