Blitz mutations are plain, asynchronous JavaScript functions that always run on the server.
1. Mutations must be inside a mutations
folder. All of the following
are valid:
src/mutations/createProject.ts
src/projects/mutations/createProject.ts
src/admin/projects/mutations/createProject.ts
2. Mutations must export a function as the default export
You can write any normal Node.js code here, including database access and fetching from third-party APIs.
input: any
ctx: Ctx
ctx.session
with all the data about the current user
session.// app/products/mutations/createProduct.tsx
import { Ctx } from "blitz"
import db from "db"
import * as z from "zod"
const CreateProject = z
.object({
name: z.string(),
})
.nonstrict()
export default async function createProject(
input: z.infer<typeof CreateProject>,
ctx: Ctx
) {
// Validate input - very important for security
const data = CreateProject.parse(input)
// Require user to be logged in
ctx.session.$authorize()
const project = await db.project.create({ data })
// Can do any processing, fetching from other APIs, etc
return project
}
We automatically alias the root of your project, so import db from 'db'
is importing <project_root>/db/index.ts
Next, read these docs to see how to use these mutations in your components.