61 lines
1.5 KiB
Plaintext
61 lines
1.5 KiB
Plaintext
---
|
|
description: Writing Server Actions for mutating data
|
|
globs: apps/**","packages/**
|
|
alwaysApply: false
|
|
---
|
|
# Server Actions
|
|
|
|
- For Data Mutations from Client Components, always use Server Actions
|
|
- Always name the server actions file as "server-actions.ts"
|
|
- Always name exported Server Actions suffixed as "Action", ex. "createPostAction"
|
|
- Always use the `enhanceAction` function from the "@kit/supabase/actions" package [index.ts](mdc:packages/next/src/actions/index.ts)
|
|
|
|
```tsx
|
|
'use server';
|
|
import { z } from 'zod';
|
|
import { enhanceAction } from '@kit/next/actions';
|
|
|
|
const ZodSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(6),
|
|
});
|
|
|
|
export const myServerAction = enhanceAction(
|
|
async function (data, user) {
|
|
// 1. "data" is already a valid ZodSchema and it's safe to use
|
|
// 2. "user" is the authenticated user
|
|
|
|
// ... your code here
|
|
return {
|
|
success: true,
|
|
};
|
|
},
|
|
{
|
|
auth: true,
|
|
schema: ZodSchema,
|
|
},
|
|
);
|
|
```
|
|
|
|
## Logging
|
|
|
|
Consider logging asynchronous requests using the `@kit/shared/logger` package in a structured way to provide context to the logs in both server actions and route handlers.
|
|
|
|
```tsx
|
|
const ctx = {
|
|
name: 'my-server-action', // use a meaningful name
|
|
userId: user.id, // use the authenticated user's ID
|
|
};
|
|
|
|
logger.info(ctx, 'Request started...');
|
|
|
|
const { data, error } = await supabase.from('notes').select('*');
|
|
|
|
if (error) {
|
|
logger.error(ctx, 'Request failed...');
|
|
// handle error
|
|
} else {
|
|
logger.info(ctx, 'Request succeeded...');
|
|
// use data
|
|
}
|
|
``` |