7 Server Actions

Server Actions

Check this guide (opens in a new tab) to learn more about server actions and mutations.

  1. Create a Next.js application then install and setup Prisma.

  2. Create a schema for managing a collection of records. A record has an automatically-generated identifier and a required title:

    prisma/schema.prisma
    generator client {
      provider = "prisma-client-js"
    }
     
    datasource db {
      provider = "sqlite"
      url      = env("DATABASE_URL")
    }
     
    model Record {
      id    String @id @default(cuid(2))
      title String
    }
  3. Create a CRUD data repository service to manage records:

    repos/records.js
    import prisma from "@/repos/prisma";
     
    export async function read(id) {
      if (id) {
        return await prisma.record.findMany({ where: { id } });
      }
      return await prisma.record.findMany();
    }
     
    export async function create(data) {
      return await prisma.record.create({ data });
    }
  4. Create a page that allows a user to manage their ideas, using server actions to retrieve, create, and delete records. Do not store the records using web storage!

    app/actions.js
    "use server";
     
    import { revalidatePath } from "next/cache";
    import * as records from "@/repos/records";
     
    export async function get(id) {
      return await records.read(id);
    }
     
    export async function add(data) {
      const record = await records.create(data);
      revalidatePath(`/`);
      return record;
    }

Resources