Complete Wasp operations patterns for queries and actions. Use when creating backend operations, implementing queries/actions, or working with server-side code...
When to use this skill:
Key concepts:
Location: app/main.wasp
Query declaration (READ operations):
query getTasks {
fn: import { getTasks } from "@src/server/tasks/operations",
entities: [Task] // REQUIRED for context.entities + auto-invalidation
}
query getTask {
fn: import { getTask } from "@src/server/tasks/operations",
entities: [Task]
}
Action declaration (WRITE operations):
action createTask {
fn: import { createTask } from "@src/server/tasks/operations",
entities: [Task] // Same entities as getTasks ā auto-invalidates getTasks!
}
action updateTask {
fn: import { updateTask } from "@src/server/tasks/operations",
entities: [Task] // Auto-invalidates getTasks query
}
action deleteTask {
fn: import { deleteTask } from "@src/server/tasks/operations",
entities: [Task] // Auto-invalidates getTasks query
}
Critical rules:
@src/ prefix in main.wasp imports (NOT relative paths)entities: [...] arrayLocation: app/src/{feature}/operations.ts (one file per feature)
Required imports:
import { HttpError } from "wasp/server";
import type {
GetTasks,
GetTask,
CreateTask,
UpdateTask,
DeleteTask,
} from "wasp/server/operations";
import type { Task } from "wasp/entities";
Import rules:
wasp/server for HttpErrorwasp/server/operations for type annotationswasp/entities for entity types@wasp/... (wrong prefix)@src/... in .ts files (use relative paths)/**
* Get all tasks for authenticated user
*
* Features:
* - Auth check
* - Optional filtering
* - Returns array
*/
export const getTasks: GetTasks<
{ status?: string }, // Args type
Task[] // Return type
> = async (args, context) => {
// 1. ALWAYS check auth first (MANDATORY)
if (!context.user) throw new HttpError(401);
// 2. Build query with optional filters
const where: any = { userId: context.user.id };
if (args.status) {
where.status = args.status;
}
// 3. Query with context.entities (enabled by type annotation + entities in main.wasp)
return context.entities.Task.findMany({
where,
orderBy: { createdAt: "desc" },
include: {
// Include related entities to avoid N+1 queries
user: {
select: { id: true, username: true },
},
},
});
};
Key points:
GetTasks<Args, Return> is CRITICALcontext.entities is undefined!/**
* Get single task by ID
*
* Features:
* - Auth check
* - Resource existence check (404)
* - Permission check (403)
* - Returns single entity or throws
*/
export const getTask: GetTask<
{ id: string }, // Args type
Task // Return type
> = async (args, context) => {
// 1. Auth check
if (!context.user) throw new HttpError(401);
// 2. Fetch resource
const taskRecord = await context.entities.Task.findUnique({
where: { id: args.id },
include: {
user: {
select: { id: true, username: true },
},
},
});
// 3. Check existence (404)
if (!taskRecord) {
throw new HttpError(404, "Task not found");
}
// 4. Check permission (403)
if (taskRecord.userId !== context.user.id) {
throw new HttpError(403, "Not authorized to access this task");
}
// 5. Return resource
return taskRecord;
};
Error sequence (CRITICAL):
Always check in this order!
/**
* Create new task
*
* Features:
* - Auth check
* - Input validation
* - Auto-invalidates getTasks query
* - Returns created entity
*/
export const createTask: CreateTask<
{ description: string; status?: string }, // Args type
Task // Return type
> = async (args, context) => {
// 1. Auth check
if (!context.user) throw new HttpError(401);
// 2. Validate input
if (!args.description?.trim()) {
throw new HttpError(400, "Description is required");
}
if (args.description.length > 500) {
throw new HttpError(400, "Description must be 500 characters or less");
}
// 3. Create entity
const taskRecord = await context.entities.Task.create({
data: {
description: args.description.trim(),
status: args.status || "TODO",
userId: context.user.id,
},
});
// 4. Return created entity
// Note: getTasks query auto-refetches if entities match in main.wasp
return taskRecord;
};
Auto-invalidation magic:
entities: [Task]entities: [Task]/**
* Update existing task
*
* Features:
* - Auth check
* - Resource existence check
* - Permission check
* - Input validation
* - Partial updates
*/
export const updateTask: UpdateTask<
{ id: string; data: { description?: string; status?: string } },
Task
> = async (args, context) => {
// 1. Auth check
if (!context.user) throw new HttpError(401);
// 2. Fetch existing resource
const taskRecord = await context.entities.Task.findUnique({
where: { id: args.id },
});
// 3. Check existence (404)
if (!taskRecord) {
throw new HttpError(404, "Task not found");
}
// 4. Check permission (403)
if (taskRecord.userId !== context.user.id) {
throw new HttpError(403, "Not authorized to update this task");
}
// 5. Validate input (if provided)
if (args.data.description !== undefined) {
if (!args.data.description.trim()) {
throw new HttpError(400, "Description cannot be empty");
}
if (args.data.description.length > 500) {
throw new HttpError(400, "Description must be 500 characters or less");
}
}
// 6. Update entity
const updatedTask = await context.entities.Task.update({
where: { id: args.id },
data: {
...(args.data.description && {
description: args.data.description.trim(),
}),
...(args.data.status && { status: args.data.status }),
},
});
// 7. Return updated entity
return updatedTask;
};
Partial update pattern:
/**
* Delete task
*
* Features:
* - Auth check
* - Resource existence check
* - Permission check
* - Returns deleted entity
*/
export const deleteTask: DeleteTask<{ id: string }, Task> = async (
args,
context,
) => {
// 1. Auth check
if (!context.user) throw new HttpError(401);
// 2. Fetch existing resource
const taskRecord = await context.entities.Task.findUnique({
where: { id: args.id },
});
// 3. Check existence (404)
if (!taskRecord) {
throw new HttpError(404, "Task not found");
}
// 4. Check permission (403)
if (taskRecord.userId !== context.user.id) {
throw new HttpError(403, "Not authorized to delete this task");
}
// 5. Delete entity
const deletedTask = await context.entities.Task.delete({
where: { id: args.id },
});
// 6. Return deleted entity
return deletedTask;
};
Location: app/src/{feature}/components/*.tsx
Required imports:
import {
useQuery,
createTask,
updateTask,
deleteTask,
} from "wasp/client/operations";
Query usage (useQuery hook):
function TasksPage() {
// Use useQuery hook for queries
const {
data: tasks, // Task[] | undefined
isLoading, // boolean
error // Error | undefined
} = useQuery(getTasks, { status: 'TODO' }) // Optional args
// Handle loading state
if (isLoading) return <div>Loading...</div>
// Handle error state
if (error) return <div>Error: {error.message}</div>
// Handle empty state
if (!tasks || tasks.length === 0) return <div>No tasks</div>
// Render data
return (
<div>
{tasks.map((task) => (
<TaskItem key={task.id} task={task} />
))}
</div>
)
}
Action usage (direct async/await - DEFAULT):
function TaskForm() {
const handleCreate = async (description: string) => {
try {
// ā
CORRECT - Direct call (default approach)
await createTask({ description, status: "TODO" });
toast.success("Task created");
// Wasp auto-refetches getTasks query!
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create task");
}
};
const handleUpdate = async (id: string, data: any) => {
try {
await updateTask({ id, data });
toast.success("Task updated");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to update task");
}
};
const handleDelete = async (id: string) => {
try {
await deleteTask({ id });
toast.success("Task deleted");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to delete task");
}
};
// ... rest of component
}
CRITICAL: DO NOT use useAction by default!
// ā WRONG - useAction by default
const createTaskFn = useAction(createTask);
await createTaskFn(data);
// Blocks auto-invalidation, adds unnecessary complexity
// ā
CORRECT - Direct call
await createTask(data);
// Simpler AND enables auto-invalidation
ONLY use useAction for optimistic UI updates (advanced):
// Advanced pattern - optimistic updates
const deleteTaskFn = useAction(deleteTask, {
optimisticUpdates: [
{
getQuerySpecifier: () => [getTasks],
updateQuery: (oldTasks, { id }) => {
return oldTasks.filter((task) => task.id !== id);
},
},
],
});
const handleOptimisticDelete = async (id: string) => {
try {
// UI updates immediately (optimistic)
// Query refetches in background (actual)
await deleteTaskFn({ id });
toast.success("Task deleted");
} catch (err) {
// Optimistic update reverted if error
toast.error("Failed to delete task");
}
};
When to use optimistic updates:
After adding/modifying operations in main.wasp:
# Stop current wasp process (Ctrl+C), then safe-start (multi-worktree safe)
../scripts/safe-start.sh
Why restart is needed:
Common error if you forget:
Cannot find module 'wasp/server/operations'
or
Property 'Task' does not exist on type 'Context'
Fix: Stop wasp (Ctrl+C) and run ../scripts/safe-start.sh (multi-worktree safe)
/**
* Check if user can access resource based on multiple criteria
*/
async function canAccessTask(
userId: string,
taskId: string,
context: any,
): Promise<boolean> {
const taskRecord = await context.entities.Task.findUnique({
where: { id: taskId },
include: {
project: {
include: {
members: true,
},
},
},
});
if (!taskRecord) return false;
// Owner can access
if (taskRecord.userId === userId) return true;
// Project members can access
if (taskRecord.project?.members.some((m: any) => m.userId === userId)) {
return true;
}
// Organization admins can access
const userRole = await getUserOrgRole(userId, task.organizationId, context);
if (["OWNER", "ADMIN"].includes(userRole)) return true;
return false;
}
// Usage in operation
export const getTask: GetTask<{ id: string }, Task> = async (args, context) => {
if (!context.user) throw new HttpError(401);
const hasAccess = await canAccessTask(context.user.id, args.id, context);
if (!hasAccess) throw new HttpError(403, "Not authorized");
return context.entities.Task.findUnique({ where: { id: args.id } });
};
import { z } from "zod";
const CreateTaskSchema = z.object({
description: z.string().min(1, "Description required").max(500, "Too long"),
status: z.enum(["TODO", "IN_PROGRESS", "DONE"]).optional(),
dueDate: z.string().datetime().optional(),
});
export const createTask: CreateTask = async (args, context) => {
if (!context.user) throw new HttpError(401);
try {
const validated = CreateTaskSchema.parse(args);
return await context.entities.Task.create({
data: { ...validated, userId: context.user.id },
});
} catch (error) {
if (error instanceof z.ZodError) {
const messages = error.errors.map(
(e) => `${e.path.join(".")}: ${e.message}`,
);
throw new HttpError(400, messages.join(", "));
}
throw error;
}
};
Benefits:
export const getTasks: GetTasks<
{ page?: number; pageSize?: number },
{ tasks: Task[]; total: number; hasMore: boolean }
> = async (args, context) => {
if (!context.user) throw new HttpError(401);
const page = args.page || 0;
const pageSize = args.pageSize || 20;
const [tasks, total] = await Promise.all([
context.entities.Task.findMany({
where: { userId: context.user.id },
skip: page * pageSize,
take: pageSize,
orderBy: { createdAt: "desc" },
}),
context.entities.Task.count({
where: { userId: context.user.id },
}),
]);
return {
tasks,
total,
hasMore: (page + 1) * pageSize < total,
};
};
Key points:
skip and take for paginationexport const deleteMultipleTasks: DeleteMultipleTasks<
{ ids: string[] },
{ count: number }
> = async (args, context) => {
if (!context.user) throw new HttpError(401);
// Verify user owns all tasks
const tasks = await context.entities.Task.findMany({
where: { id: { in: args.ids } },
});
const unauthorized = tasks.filter((task) => task.userId !== context.user.id);
if (unauthorized.length > 0) {
throw new HttpError(403, "Not authorized to delete some tasks");
}
// Bulk delete
const result = await context.entities.Task.deleteMany({
where: {
id: { in: args.ids },
userId: context.user.id,
},
});
return { count: result.count };
};
Security note:
deleteMany only after permission checkCause: Using wrong import prefix or forgot to restart
Solutions:
wasp/... NOT @wasp/...../scripts/safe-start.sh (multi-worktree safe)// ā WRONG
import { Task } from "@wasp/entities";
// ā
CORRECT
import { Task } from "wasp/entities";
Cause: Missing type annotation or entity not listed in main.wasp
Solutions:
GetTasks<Args, Return>entities: [Task]// ā WRONG - No type annotation
export const getTasks = async (args, context) => {
return context.entities.Task.findMany(); // context.entities is undefined!
};
// ā
CORRECT - With type annotation
export const getTasks: GetTasks<void, Task[]> = async (args, context) => {
return context.entities.Task.findMany(); // Works!
};
Cause: Query and action have different entities lists
Solution: Use same entities in both
// ā WRONG - Different entities
query getTasks {
entities: [Task]
}
action createTask {
entities: [Task, User] // Extra entities prevent auto-invalidation
}
// ā
CORRECT - Same entities
query getTasks {
entities: [Task]
}
action createTask {
entities: [Task] // Matches query ā auto-invalidation works!
}
Cause: Using wrong helper to access auth fields
Solution: Use Wasp helpers for email/username
// ā WRONG - Direct access
if (context.user.email === 'admin@example.com') { ... } // UNDEFINED!
// ā
CORRECT - Use helper
import { getEmail } from 'wasp/auth'
const email = getEmail(context.user)
if (email === 'admin@example.com') { ... } // Works!
Add type annotations
GetQuery<Args, Return>CreateAction<Args, Return>Check auth FIRST
if (!context.user) throw new HttpError(401)List entities in main.wasp
Use direct await for actions (default)
await createTask(data) (simple, enables auto-invalidation)useAction(createTask) (only for optimistic UI)Restart after main.wasp changes
../scripts/safe-start.sh (multi-worktree safe)Follow error sequence
Avoid N+1 queries
include for relationsValidate input
Skip type annotations
Skip auth check
Use useAction by default
Forget to restart
Use @wasp/ prefix
wasp/entities@wasp/entitiesUse @src/ in .ts/.tsx files
../../utils/helper@src/utils/helperAccess user.email directly
getEmail(user)user.email (undefined!)Mix up enum imports
import type { UserRole } from 'wasp/entities'import { UserRole } from '@prisma/client'See .claude/templates/operations-patterns.ts for copy-paste ready examples:
Need to fetch data from server?
āā YES ā Create QUERY
ā 1. Add query block to main.wasp
ā 2. Implement with GetQuery<Args, Return> type
ā 3. Use useQuery hook in client
ā
āā NO ā Need to modify data?
āā YES ā Create ACTION
1. Add action block to main.wasp
2. Implement with CreateAction<Args, Return> type
3. Use direct await in client (NOT useAction)
This skill provides complete Wasp operations implementation guidance.
Key takeaways:
When stuck:
../scripts/safe-start.sh restarted after changes (multi-worktree safe)For complete examples: See .claude/templates/operations-patterns.ts