Subscribe for Free Tips, Tutorials, and Special Discounts
We're in this together!
We respect your privacy. Unsubscribe at any time.
Question: Should I use Server Actions or APIs?
Answer: What a great question! There are two different ways for the client to communicate back to the NextJS server that are supported by the App Router; API routes and Server Actions.
API routes are highly customizable endpoints that can support all the HTTP verbs and respond with any kind of payload. The downside of APIs is that they aren't inherintely type-safe.
Server Actions, on the other hand, are type-safe out of the box when you use them within the context of the NextJS application. The issue with server actions is that you don't get as much control over the format of the payload.
In my opinion the decision rests on whether you have an external client that is also going to want to make calls to these interfaces. For example you might also be writing a React-Native application that wants to use the endpoints provided by the NextJS application. If that is the case then I would steer you towards using API routes because you control the API format.
It is possible for a React-Native application to talk to the server action endpoints, they are just API endpoints. But it will have to imitate the type of calls created on the client. That's not great. If NextJS changes the format from version to version it will break the React-Native app but not break the NextJS client code.
The nice thing about NextJS is that you can always use both mechanisms at the same time. So you could start with Server Actions and then migrate over to, or just add on, API endpoints as you need them.
Share this article with your friends
Written by Jack Herrington
Jack Herrington is a Full Stack Principal Engineer who orchestrated the rollout of React/NextJS at Walmart Labs and Nike. He is also the "Blue Collar Coder" on YouTube where he posts weekly videos on advanced use of React and NextJS as well as other frontend technologies trends. His YouTube channel hosts an entire free courses on React and TypeScript. He has written seven books including most recently No-BS TypeScript which is a companion book to the YouTube course.