DevFlow

Dev Overflow

How secure are NextJs Server Actions?

clock icon

asked 10 months ago

message

1 Answers

eye

10 Views

Can someone please explain me how do Server Actions work under the hood? In the following example, i first check if the viewer has access to the account and then create the Action. This works fine in a browser. But what happens if someone forges a request that fakes the 'submit' call? Do i need to do another check inside the Action? If i add another 'if' in the Action, TypeScript tells me that the variable is always true at that point and i don't need to worry about it. Is this true or is TypeScript trying to fool me? Documentation says that we need to check if the user has rights to perform the action but the example is outside of components. Does it work the same in Server Components?

 

async function DeleteUser({ targetUser }: Props) {
  if (!hasViewerAccess(targetUser)) return "403 forbidden";

  const submit = async () => {
    "use server";

    deleteUser(targetUser);
  };

  return (
    <form action={submit}>
      <input type="submit" value="Delete" />
    </form>
  );
}

1 Answers

Yes, you should always check whether a user is allowed to perform a server action inside it.

As Next.js docs says,

You should treat Server Actions as you would public-facing API endpoints, and ensure that the user is authorized to perform the action.

Under the hood, your app is doing a POST request to invoke your submit action with its arguments and the application context. Thus you need to authenticate the request before doing anything.

Top Questions