I have server bunch of server actions ( createProduct ,getProductAssets .. ) and each of that checks user sessions if its valid request first.
I want to check session only once if its valid then call the wanted function…
So how should I structure my product-actions/index file ?
one of functions
export async function getProductAssets(productId: string) {
try {
const session: Session = await getServerSession(authOptions);
if (!session.user) {
return {
success: false,
message: 'Unauthorized!',
};
}
....
2
Answers
this does not make sense. because, server actions are aync functions that run exclusively on the server, invoked by user interactions on the client side. If a server sction performs sensitive actions like accessing private resources, verifying the user’s session ensures that only authorized users can execute those actions.
let’s say you checked the session first and you got a valid session. But after 2 minutes user invoked another action, maybe
createProduct
action, if the session expired at that time and you do not check session, anyone could potentially forge requests to create products, even if not logged in or authorized. this could lead to unauthorized product listingsIf you were using api routes you could use middleware, with server actions I dont think its possible, not easily anyway. One way would be to abstract the auth code into a function and make it short and sweet, checkSession(session). But really, there shouldnt be a function call in the first place if they are not authed.