Express-Like Auth Middleware Pattern For Server Actions?
Since all server actions should be authenticated, I have sprinkled clerk's auth() function at the top of every single action's function body. This seems silly. I liked how Express allows you to apply an auth middleware to collections of routes. For instance:
One possible solution is to extract the auth into a wrapper function and wrap each server action with it. Still a alot of repetition. Another solution could be to export the protected server actions to an index file and wrap that the withAuth wrapper function.
Are there any other patters? I love server actions, but am missing traditional auth middleware.
6 Replies
you can use a library like zsa for a trpc like experience
https://zsa.vercel.app/docs/procedures
check this out. the first example is exactly the pattern u want
@Ahmed Senousy Thank you! This is basically tRPC without the crazy set up.
yesss
I fell in love once I saw it 😂❤️
@Ahmed Senousy I've been doing some research and another option is adding policies if you are using Postgres. For instance, you can enforce that the user is editing a post that it owns. I guess its up to the developer about whether the check should be at the api level or the DB level
I'm not a big fan of row level security but yes it can be done using that too ig
I like to keep my auth logic in my service layer (backend) and keep my db for only r/w
yea, its definitely easier to debug if the logic is in the action, but you are making an extra query to the database each time the user modifies data