Next.js Discord

Discord Forum

Question regarding Server Action and API

Unanswered
SupremeDeity posted this in #help-forum
Open in Discord
Avatar
SupremeDeityOP
Context: i currently have a full api written using Route Handlers and i am currently doing something considered an anti-pattern which is using these Route Handlers inside Server Components.

I had some headaches previously due to this and thought maybe I'll just shift everything to Server Actions where possible.

However the question is:

When i want to make parts of my api public wont i basically end up with duplicate code(one for api route and one for server action) or in another case, if i call my server action in my route handler(if thats even possible), I would still end up with a supposed anti-pattern?

How do i get around this?

11 Replies

Avatar
Alfonsus Ardani
When i want to make parts of my api public wont i basically end up with duplicate code(one for api route and one for server action) or in another case, if i call my server action in my route handler(if thats even possible), I would still end up with a supposed anti-pattern?


As long as you protect your server action with Auth, its okay to call server action anywhere
As long as you keep in mind, for every export async function you write in "use server" file, they EXPOSES an endpoint in the server and available for anyone to connect.
Avatar
SupremeDeityOP
ahh, you see thats gonna be a problem. Currently i use Auth0 and it has a function to directly protect API Routes, meaning i'll probably have to think about ways to protect that too.
Another thing is, which is my main question from above is: wont i basically have to write twice to make my api correctly public? IIRC server actions only work on POST actions and it wont really be a REST API then
Avatar
Alfonsus Ardani
yeah
either you write 1 function and use that in route handler + server action
or reuse server action and auth guard twice, both in server action and route handler
Avatar
Ray
I would use trpc. you define the logic in procedure then you can use the caller in server action while still have the api endpoint
Avatar
SupremeDeityOP
Honestly Trpc would be one of the ways but i have 0 experience in it and i feel like converting all the code into tRPC is gonna be really hard.

Also since im not the only one working on this specific project its going to introduce one more library the other person will have to familiarize themselves with
I am going to have to sit down and plan this out ig since some rules regarding internal api and public api will have to differ like the method of authorization.
Avatar
Alfonsus Ardani
then its not implementing twice if the method of auth differs :noice: