Next.js Discord

Discord Forum

Should I use "use server" directive for database queries

Answered
Brewer's Blackbird posted this in #help-forum
Open in Discord
Brewer's BlackbirdOP
"use server"

import { db } from "~/server/db";

export async function getArticle(id: string) {
  const article = await db.article.findUnique({
    where: { id, published: true },
    select: {
      title: true,
      description: true,
      content: true,
      tag: true,
      createdAt: true,
      author: {}
    },
  });
}


If I remove the directive, it would still be running on server and everything is safe, right?
Answered by joulev
You should only use “use server” when it is required. Because using that directive means your function effectively becomes a public api route, you should not overuse it and if you use it you must equip your function with sufficient authentication, authorisation, rate limiting, validation, etc you name it.

In this case since probably you will run this in a server component, the directive is not necessary so you should not use it.
View full answer

9 Replies

@Brewer's Blackbird ts "use server" import { db } from "~/server/db"; export async function getArticle(id: string) { const article = await db.article.findUnique({ where: { id, published: true }, select: { title: true, description: true, content: true, tag: true, createdAt: true, author: {} }, }); } If I remove the directive, it would still be running on server and everything is safe, right?
You should only use “use server” when it is required. Because using that directive means your function effectively becomes a public api route, you should not overuse it and if you use it you must equip your function with sufficient authentication, authorisation, rate limiting, validation, etc you name it.

In this case since probably you will run this in a server component, the directive is not necessary so you should not use it.
Answer
@Brewer's Blackbird I would like to know when should I use the "use server" directive. Is it meant to be used only in server actions?
Yes. Only use it for when you need to expose a function for it to be callable by anyone
@joulev Yes. Only use it for when you need to expose a function for it to be callable by anyone
Brewer's BlackbirdOP
The article page is rendered on the server, so there's no need to use "use server"
But what if the page is rendered on the client side, and user need other data
Then, is the "use server" necessary
@Brewer's Blackbird The article page is rendered on the server, so there's no need to use "use server"
If you use client side rendering by fetching something during an onClick event for example then yes, server action is a good idea
Basically it just makes your function a publicly available api route that your frontend can fetch
Brewer's BlackbirdOP
Thanks