Next.js Discord

Discord Forum

When to use server actions

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hello everyone, I am having a hard time figuring out when server actions are useful. Before we would just interact with a provided API using form handlers, with the introduction of server actions I don't know when to use form handlers anymore and when to apply server actions.

What is a good rule of thumb? On top of that I see people directly interacting with the database whenever server actions are used, so is having an API for the frontend no longer needed since we can directly interact with the database? When would I need to create my own API? Or is it more of a combination of both.

Thanks in advance. If you can (and have time) provide an as much detailed answer as you can.
Answered by Arinji
Its the same functionality for server actions, it just feels better since it's just a function you call + no need to fetch random urls. Dx improcements
View full answer

9 Replies

@B33fb0n3 I like to use them when I have **mutations from client**. If I need external access or anything else I can use route handlers
Cape lionOP
Do you directly interact with the database in such a case or do you still have a layer in between to communicate with the database in that manner?
like a controller for example
@Cape lion have you used api routes?
Its the same functionality for server actions, it just feels better since it's just a function you call + no need to fetch random urls. Dx improcements
Answer
Server actions can't be run in parallel btw
@Cape lion Do you directly interact with the database in such a case or do you still have a layer in between to communicate with the database in that manner?
I do them same as I would when server actions don’t exists and I need to use route handlers. One thing that I do differently when using server actions is, that I validate the user input effectively thought zod. I validate only important fields when using route handlers. Validating the user input should still be a priority
@Arinji <@142397529336578049> have you used api routes?
Cape lionOP
ah yes thinking of it this way makes a lot of sense, thank you