Using server actions to replace route handlers?
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
After version 14 I became curious to see if I could use server actions instead of route handlers to handle authentication state and database calls. I managed to make user login and logout to work with server actions. But when I moved on to handling registering a new user account, I realized that server actions don't support the request API that I needed to build a callback URL for the verification email:
I became suspicious about server actions being a suitable solution for my use case. After some googling it is still unclear to me when to use server actions and when route handlers. What can server actions do that route handlers can't? Are there any clear indicators for choosing one over the other?
`${new URL(request.url).origin}/auth/callback`I became suspicious about server actions being a suitable solution for my use case. After some googling it is still unclear to me when to use server actions and when route handlers. What can server actions do that route handlers can't? Are there any clear indicators for choosing one over the other?
9 Replies
Dunker
basically server actions for forms, and things happen on server in client component like data updating.
if server actions are not solving your problems, you can look for route handlers, if you need structured api routes and controller logic, route handlers are better
if server actions are not solving your problems, you can look for route handlers, if you need structured api routes and controller logic, route handlers are better
Server Actions are "actions" = response to user actions
but to communicate with other servers eg to implement auth callbacks you still need a Route Handler or API Route
@Eric Burel but to communicate with other servers eg to implement auth callbacks you still need a Route Handler or API Route
Polar bearOP
Why do I need a route handler for that?
@Polar bear Why do I need a route handler for that?
the server action is like an endpoint totally internal to your Next.js application
so external APIs cannnot call them
if you need to craft a webhook or auth callback you may need to provide an URL to call, so an API route/route handler
Polar bearOP
I can communicate with my auth provider in a server action just fine
Polar bearOP
So far the biggest drawback to me is the lack of Request/Response API:s. In practice it takes a bit more effort to determine things like referrer URL and locale, as well as to structure response values in cases where I need a client handler for state updates, error handling etc. These I found were easier to deal with using route handlers. Other than that, server actions are very convenient especially because I don't have to build api routes.