Next.js Discord

Discord Forum

Is it possible to access server actions like API calls?

Answered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I am interested in this more from a security standpoint. If I had a dangerous server action that I only had a use on the server for example:

"use server"
export async function deleteUser(userId: string) {
  await db.from(Users).delete(userId)
}


Could it be somehow accessible from the outside like an API call for example?

In the function that user interacts with I would have auth checking with another primitive function validateRequest like this:

"use server"
import { validateRequest } from "auth-actions"
import { deleteUser, deleteUserPosts } from "user-actions"

export async function banUser(session: Session, userId: string) {
  const isAuthenticated = await validateRequest(session)

  if (!isAuthenticated) return

  await deleteUser(userId)
  await deleteUserPosts(userId)
}


If deleteUser was an API route it would be unsafe since anyone could POST a userId and delete a user, so I am wondering if it is the same with server actions?
Answered by Jboncz
Yes if someone was able to determine what the random value that was generated was they could. Server actions still go through middleware, you should be validating authentication either in middleware or in the server action itself. ( check sesssion, cookies, token whatever)
View full answer

7 Replies

Yes if someone was able to determine what the random value that was generated was they could. Server actions still go through middleware, you should be validating authentication either in middleware or in the server action itself. ( check sesssion, cookies, token whatever)
Answer
You dont need the first snippet to be a server action, it should remain server side and only be called by a server action.
Sun bearOP
ohh so I can make primitives without "use server" and they would be safe?
I really dislike the middleware so I would try to avoid it as much as possible
Yeah, the only thing that needsd the 'user server' directive is whats being called from the client, I wrap all server side code in a server action if im going to use it instead of calling it directly
Once your on the server you can do whatever you want
Sun bearOP
thank you