#need to clarify something
1 messages · Page 1 of 1 (latest)
Based on the knowledge sources provided, your approach seems to be in line with the constraints of Next.js server actions.
In Next.js, server actions must be asynchronous functions, and they cannot be classes. However, there's no restriction on using classes within those functions. Your approach of creating a wrapper function that calls a method on a class should work fine.
However, there are a few things to keep in mind:
- Server actions are treated like public-facing API endpoints. Therefore, you should ensure that the user is authorized to perform the action. You can do this by checking the user's authentication status within the server action. Here's an example from the Next.js documentation:
'use server'
import { auth } from './lib'
export function addItem() {
const { user } = auth()
if (!user) {
throw new Error('You must be signed in to perform this action')
}
// ...
}
- If you're using ESM packages in your server actions, you might encounter issues when trying to use classes from those packages. A workaround suggested in one of the GitHub issues is to inline the import:
new (await import("oslo/password")).Argon2id();
Source (https://github.com/vercel/next.js/issues/60756)
Please note that these are general guidelines and the actual implementation might vary based on your specific use case and the packages you're using.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@stiff violet kapa.ai is still learning and improving, please let us know how it did by reacting below
@dapper sleet i am getting the auth status from the getaccesstoken function
Let me check the knowledge base for you. One moment! :books:
That's great! If you're using a function like getAccessToken() to manage authentication, you can continue to use that within your server actions. Just ensure that this function is correctly validating the user's authentication status.
Here's an example of how you might use such a function within a server action:
"use server"
export async function addIdeation({{
teamId,
title,
description,
vision,
}}: AddIdeationUsecaseDto): Promise<
AsyncActionResponse<AddIdeationResponseDto>
> {{
const addIdeationClientAdapter = new IdeationClientAdapter();
const token = getAccessToken();
if (!token) {
throw new Error('You must be signed in to perform this action');
}
return addIdeationClientAdapter.addIdeation({{
teamId,
title,
description,
vision,
}});
}}
In this example, if getAccessToken() returns null or undefined (indicating that the user is not authenticated), an error is thrown. This prevents the rest of the server action from executing.