next.jsserver-action

Trouble Understanding the Benefit/Point of Server Actions in Next.js


I don't understand the importance of Server Actions in Next.js. For example take a look at the following code.

import prisma from '@/utils/db';

const PrismaExamplePage: React.FunctionComponent = async() => {
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
    return (
        <h1>Prisma Example Page</h1>
    );
}

export default PrismaExamplePage;

Everything works. Then I see people do the same thing using Server Actions

import prisma from '@/utils/db';

const createTask = async() => {
    "use server";
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
}

const PrismaExamplePage: React.FunctionComponent = async() => {
    await createTask();
    return (
        <h1>Prisma Example Page</h1>
    );
}

export default PrismaExamplePage;

What is the difference between me using Server Actions and not using Server Actions. I don't see the benefit or the point

I've heard some people argue that it makes the code readable but thats not a good answer. Because I can also make the code more readable and not use a server action.

import prisma from '@/utils/db';

const createTask = async() => {
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
}
    
const PrismaExamplePage: React.FunctionComponent = async() => {
    await createTask();
    return (
        <h1>Prisma Example Page</h1>
    );
}
    
export default PrismaExamplePage;

Solution

  • some benefit of server actions :