reactjsnext.jsnext.js13

Server actions vs API routes - when to use what


I started to learning Next.js and one think that I don't really understand or can't even find good answer when to use server actions and when to use API routes. Im building project where I would like to focus on using best practices when it comes to Next.js - just project to learn something new.

Ive used server actions for functionality that can be handled close to the server - for example form submitting when creating blog post. Same goes for updating and deleting of the post. But how about something like getting all the post from database? is it good idea to also use server action or is this scenario that should be handled by API routes?

If I should use server actions for getting the data, then what's the point of using API routes in newer version of Next.js? except like exposing data using endpoint to 3rd party service (just an example)

This is something that I still don't understand - when to use this over that.

I found this topic: Nextjs 14: Server actions vs Route handlers

But there is no answer why should I use API routes when server action does the same job (almost, at least for me).


Solution

  • You use API routes when you want to expose the data via the /API route. This might be useful when there are other apps outside of your current project that want to interact with the server.

    If not, you should use server actions.