Using With RedwoodJS
RedwoodJS is an opinionated full-stack framework that combines a set of tools and libraries and helps you build GraphQL-based applications quickly without struggling with tooling.
ZenStack provides a plugin package to help you easily integrate with RedwoodJS projects. After setting it up, you can define access policies in ZModel and use the enhanced PrismaClient to enforce the policies in your services automatically.
Details
Setting up
You can prepare your RedwoodJS project for ZenStack by running the following command at the root of your project:
yarn rw setup package @zenstackhq/redwood
The setup command will:
-
Update "redwood.toml" to allow the ZenStack CLI plugin
[[experimental.cli.plugins]]
package = "@zenstackhq/redwood"
enabled = true -
Install ZenStack dependencies to the "api" package
zenstack: the main CLI@zenstackhq/runtime: the runtime library for creating enhancedPrismaClient@zenstackhq/redwood: custom CLI and runtime for RedwoodJS
-
Prepare ZModel schema
Your Prisma schema file "api/db/schema.prisma" will be copied to "api/db/schema.zmodel". Moving forward, you should edit "schema.zmodel" to update the database schema and access policies. The "schema.prisma" file will be regenerated when you run
yarn rw @zenstackhq generate. -
Register the location of "schema.zmodel" and "schema.prisma" in "api/package.json"
api/package.json{
...
"zenstack": {
"schema": "db/schema.zmodel",
"prisma": "db/schema.prisma"
}
} -
Install a GraphQLYoga plugin to the GraphQL handler
api/src/functions/graphql.[ts|js]import { useZenStack } from '@zenstackhq/redwood'
import { db } from 'src/lib/db'
import { createGraphQLHandler } from '@redwoodjs/graphql-server'
...
export const handler = createGraphQLHandler({
...
extraPlugins: [useZenStack(db)],
})The
useZenStackplugin creates an enhancedPrismaClientfor the current requesting user and stores it asdbfield in the global GraphQL context. You can use it in your service code viacontext.db. For example, the service for listing blog posts can be implemented as follows: only posts readable to the current user will be returned.api/src/services/posts/posts.jsexport const posts = (...args) => {
return context.db.post.findMany()
}The plugin, by default, uses
context.currentUserto get the current requesting user. You can customize it by passing in a function as the second argument to calculate a custom user object based oncontext.currentUser. E.g.:useZenStack(db, async (currentUser) => {
const typedUser = currentUser as { id: string };
const dbUser = await db.user.findUnique({
where: { id: typedUser.id },
// select more fields
select: { id: true, role: true }
});
return dbUser;
});See here for more details about accessing the current user.
-
Eject service templates
The setup runs
yarn rw setup generator serviceto eject template files used byyarn rw g servicecommand. It also modifies the templates to usecontext.dbinstead ofdbto access the database with automatic access policy enforcement.
Modeling data and access policies
ZenStack's ZModel language is a superset of Prisma schema language. You should use it to define both the data schema and access policies. The Complete Guide of ZenStack is the best way to learn how to author ZModel schemas. Here's a quick example to show how you can define access policies for the blog post sample used throughout the official RedwoodJS tutorial:
model Post {
id Int @id @default(autoincrement())
title String
body String
comments Comment[]
user User @relation(fields: [userId], references: [id])
userId Int
createdAt DateTime @default(now())
published Boolean @default(true)
// 🔐 Admin user can do everything to his own posts
@@allow('all', auth().roles == 'admin' && auth() == user)
// 🔐 Posts are visible to everyone if published
@@allow('read', published)
}
You should run the following command after updating "schema.zmodel":
yarn rw @zenstackhq generate
The command does the following things:
- Regenerate "schema.prisma"
- Run
prisma generateto regeneratePrismaClient - Generate supporting JS modules for enforcing access policies at runtime
Development workflow
The workflow of using ZenStack is very similar to using Prisma in RedwoodJS projects. The two main differences are:
-
Code generation
You should run
yarn rw @zenstackhq generateinstead ofyarn rw prisma generate. The ZenStack's "generate" command internally regenerates the Prisma schema from the ZModel schema, runsprisma generateautomatically, and outputs supporting modules for access policy enforcement. -
Database access in services
In your service code, you should use
context.dbinstead ofdbfor accessing the database. The setup procedure prepared a customized service code template. When you runyarn rw g service, the generated code will already usecontext.db.
Other Prisma-related workflows like generation migration or pushing schema to the database stay unchanged.
Deployment
You should run the "generate" command in your deployment script before yarn rw deploy. For example, to deploy to Vercel, the command can be:
yarn rw @zenstackhq generate && yarn rw deploy vercel
ZenStack generates supporting JS modules into the node_modules/.zenstack folder, and the folder needs to be accessible at the runtime. Netlify detects the dependencies it needs to bundle by inspecting an application's root package.json file. This will result in the .zenstack folder being ignored.
To fix this problem, add the following section to your netlify.toml file:
[functions]
included_files = ["node_modules/.zenstack/*"]
Using the @zenstackhq CLI plugin
The @zenstackhq/redwood package registers a set of custom commands to the RedwoodJS CLI under the @zenstackhq namespace. You can run it with:
yarn rw @zenstackhq <cmd> [options]
The plugin is a simple wrapper of the standard zenstack CLI, similar to how RedwoodJS wraps the standard prisma CLI. It's equivalent to running npx zenstack ... inside the "api" directory.
See the CLI references for the complete list of commands.
Sample application
You can find a completed multi-tenant Todo application built with RedwoodJS and ZenStack at: https://github.com/zenstackhq/sample-todo-redwood.