server actions vs api routes: which one do i use? - By Sourav Mishra (@souravvmishra)
a super simple guide on when to use next.js server actions vs traditional api routes.
next.js gives us two ways to save data now: server actions and api routes.
people get confused about which one to use, so i'll make it really simple.
the quick breakdown
| Feature | Server Actions | API Routes |
|---|---|---|
| how to call | just call the function | use fetch() |
| types | works out of the box | gotta use zod/openapi |
| public access | nope | yep, anyone can call it |
| ui feel | great for forms | standard loading |
when to use server actions
if it's just for your website's ui, use server actions.
stuff like forms, like buttons, or adding to a cart. it's just way faster to write.
// action.ts
'use server';
export async function updateProfile(formData: FormData) {
// save to db
revalidatePath('/profile');
}
when to use api routes
if a mobile app, a third-party service, or a completely different website needs to talk to your backend, use an api route (app/api/...).
server actions are only for your next.js frontend.
does it matter for speed?
server actions save you from writing boring fetch code and manually handling spinners.
but if you have an endpoint that gets hit a million times a second, an api route might give you more control over caching.
read my components guide to see how i wire these up.
written by sourav mishra, just trying to keep things simple.