Next.js Discord

Discord Forum

Getting data from database: server actions

Unanswered
Brewer's Blackbird posted this in #help-forum
Open in Discord
Brewer's BlackbirdOP
Can I use server actions to get a data from database or should I create a route handler and fetch data from there.

I'm making a social media app and using new App router. In profile page I want to get user data from db like username, name, bio, image.

Here is an example:
const user = await getProfileData({ username: params.username });

  if (!user) {
    return (
      <div className="flex flex-col items-center justify-center">
        <span>Profile is not found</span>
      </div>
    );
  }


"use server";

import { zact } from "zact/server";
import { type z } from "zod";

import { prisma } from "~/lib/db";
import { getProfileDataSchema } from "~/lib/validations/user";

export async function getProfileData({
  username,
}: z.infer<typeof getProfileDataSchema>) {
  const schema = getProfileDataSchema.safeParse(username);

  if (!schema.success) {
    throw schema.error;
  }

  const user = await prisma.user.findUnique({
    where: { username },
    select: {
      name: true,
      image: true,
      username: true,
      bio: true,
    },
  });

  return user;
}


Is this the best way and do you know any libraries like zact to use queries instead of mutaitons?

3 Replies

first off, Server Action is still alpha so we cannot say what it the best practice at this moment.
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
based on the current spec, as the official doc says SA is for mutation, to update persistent storage, which can be invoked from client side JS as if it is a local function (RPC)
In App Router, fetching are done in server components rather than SA. response data can be sent as Wired Format, a chunk, via Suspense, streaming from Cloudflare Worker over HTTP/2, so in browser pages are rendered progressively.