In Next.js, you can define both server and client actions in separate files. Server actions are defined in a file with a top-level "use server" directive, and all exports below this directive will be considered server actions. Client actions, on the other hand, are defined in a file with a top-level "use client" directive.
Here's an example of how you can structure your actions.js file for server actions:
'use server'
export async function myServerAction() {
}
And here's an example for client actions:
'use client'
export function myClientAction() {
}
You can then import these actions into your components as needed. For example:
'use client'
import { myServerAction } from './actions'
import { myClientAction } from './client-actions'
export default function ClientComponent() {
}
Remember, server actions cannot be defined within client components, but they can be imported and used. Also, when using server actions, ensure that you have enabled the experimental serverActions flag in your next.config.js file.
module.exports = {
experimental: {
serverActions: true,
},
}
Please note that the server actions are designed to mutate data on the server and calling functions directly without needing to create an in-between API layer. If you're trying to set cookies in the client's browser, you might need to consider a different approach as the server actions might not be designed to handle this use case.