Modern data layer for TypeScript apps - type-safe ORM, built-in access control, automatic query services
Find a file
2024-11-04 14:44:59 -08:00
.changeset merge canary to dev (#181) 2023-01-27 22:31:44 +08:00
.github chore: add GitHub WF to push releases to Discord (#1796) 2024-10-22 08:42:37 -07:00
.vscode fix: expression context check issue on initial loading (#544) 2023-07-04 18:09:39 +08:00
packages chore: README and JetBrains changelog update (#1828) 2024-11-04 14:44:59 -08:00
script chore: upgrade to Prisma 5.21 (#1777) 2024-10-15 10:25:45 -07:00
tests feat(zmodel): "type" construct and strongly-typed Json fields (#1813) 2024-11-03 19:24:57 -08:00
.eslintignore chore: unify jest.config.ts and .eslintrc.json (#881) 2023-12-03 07:17:49 -08:00
.eslintrc.json merge v2 to dev (#1281) 2024-04-24 21:19:41 +08:00
.gitattributes (Windows) build issues and contributing docs (#1458) 2024-05-26 10:11:31 +08:00
.gitignore chore: improve test run speed (#1018) 2024-02-20 15:22:56 -08:00
.npmrc fix: use pnpm host mode to resolve tsc compatibility issues (#1613) 2024-07-25 20:47:26 -07:00
.prettierignore merge canary to dev (#181) 2023-01-27 22:31:44 +08:00
.prettierrc merge canary to dev (#181) 2023-01-27 22:31:44 +08:00
CHANGELOG.md chore: bump version and fix test (#144) 2022-12-16 16:32:03 +08:00
CODE_OF_CONDUCT.md merge canary to dev (#181) 2023-01-27 22:31:44 +08:00
CONTRIBUTING.md chore: enable corepack and upgrade pnpm (#1543) 2024-06-29 09:08:16 -07:00
jest.config.ts chore: set up ZENSTACK_TEST environment variable during test setup (#1048) 2024-02-21 17:53:32 -08:00
LICENSE dev2main: release v0.2.1 (#34) 2022-10-29 09:23:46 +08:00
package.json fix(hooks): prefer to use global fetch when available 2024-11-02 16:38:17 -07:00
pnpm-lock.yaml Make REST API ID divider configurable 2024-10-17 15:24:18 +02:00
pnpm-workspace.yaml feat: RedwoodJS integration package (#911) 2023-12-31 15:51:27 +08:00
README.md chore: README and JetBrains changelog update (#1828) 2024-11-04 14:44:59 -08:00
SECURITY.md merge canary to dev (#181) 2023-01-27 22:31:44 +08:00
test-setup.ts merge v2 to dev (#1281) 2024-04-24 21:19:41 +08:00
tsconfig.base.json chore: unify tsconfig files (#722) 2023-10-01 22:32:32 -07:00

ZenStack

What it is

ZenStack is a Node.js/TypeScript toolkit that simplifies the development of a web app's backend. It enhances Prisma ORM with a flexible Authorization layer and auto-generated, type-safe APIs/hooks, unlocking its full potential for full-stack development.

Our goal is to let you save time writing boilerplate code and focus on building real features!

How it works

Read full documentation at 👉🏻 zenstack.dev. Join Discord for feedback and questions.

ZenStack incrementally extends Prisma's power with the following four layers:

1. ZModel - an extended Prisma schema language

ZenStack introduces a data modeling language called "ZModel" - a superset of Prisma schema language. It extended Prisma schema with custom attributes and functions and, based on that, implemented a flexible access control layer around Prisma.

// base.zmodel
abstract model Base {
    id String @id
    author User @relation(fields: [authorId], references: [id])
    authorId String

    // 🔐 allow full CRUD by author
    @@allow('all', author == auth())
}
// schema.zmodel
import "base"
model Post extends Base {
    title String
    published Boolean @default(false)

    // 🔐 allow logged-in users to read published posts
    @@allow('read', auth() != null && published)
}

The zenstack CLI transpiles the ZModel into a standard Prisma schema, which you can use with the regular Prisma workflows.

2. Runtime enhancements to Prisma client

At runtime, transparent proxies are created around Prisma clients for intercepting queries and mutations to enforce access policies.

import { enhance } from '@zenstackhq/runtime';

// a regular Prisma client
const prisma = new PrismaClient();

async function getPosts(userId: string) {
    // create an enhanced Prisma client that has access control enabled
    const enhanced = enhance(prisma, { user: userId });

    // only posts that're visible to the user will be returned
    return enhanced.post.findMany();
}

3. Automatic RESTful APIs through server adapters

Server adapter packages help you wrap an access-control-enabled Prisma client into backend CRUD APIs that can be safely called from the frontend. Here's an example for Next.js:

// pages/api/model/[...path].ts

import { requestHandler } from '@zenstackhq/next';
import { enhance } from '@zenstackhq/runtime';
import { getSessionUser } from '@lib/auth';
import { prisma } from '@lib/db';

// Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc.
// Can be configured to provide standard RESTful APIs (using JSON:API) instead.
export default requestHandler({
    getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }),
});

4. Generated client libraries (hooks) for data access

Plugins can generate strong-typed client libraries that talk to the aforementioned APIs. Here's an example for React:

// components/MyPosts.tsx

import { useFindManyPost } from '@lib/hooks';

const MyPosts = () => {
    // list all posts that're visible to the current user, together with their authors
    const { data: posts } = useFindManyPost({
        include: { author: true },
        orderBy: { createdAt: 'desc' },
    });

    return (
        <ul>
            {posts?.map((post) => (
                <li key={post.id}>
                    {post.title} by {post.author.name}
                </li>
            ))}
        </ul>
    );
};

Architecture

The following diagram gives a high-level architecture overview of ZenStack.

Architecture

Features

  • Access control and data validation rules right inside your Prisma schema
  • Auto-generated OpenAPI (RESTful) specifications, services, and client libraries
  • End-to-end type safety
  • Extensible: custom attributes, functions, and a plugin system
  • A framework-agnostic core with framework-specific adapters
  • Uncompromised performance

Plugins

Framework adapters

Prisma schema extensions

Examples

Schema Samples

The sample repo includes the following patterns:

  • ACL
  • RBAC
  • ABAC
  • Multi-Tenancy

You can use this blog post as an introduction.

Multi-Tenant Todo App

Check out the Multi-tenant Todo App for a running example. You can find different implementations below:

Blog App

Community

Join our discord server for chat and updates!

Contributing

If you like ZenStack, join us to make it a better tool! Please use the Contributing Guide for details on how to get started, and don't hesitate to join Discord to share your thoughts. Documentations reside in a separate repo: zenstack-docs.

Please also consider sponsoring our work to speed up the development. Your contribution will be 100% used as a bounty reward to encourage community members to help fix bugs, add features, and improve documentation.

Sponsors

Thank you for your generous support!

Current Sponsors

Marblism
Marblism
Mermaid Chart
Mermaid Chart
CodeRabbit
CodeRabbit
Johann Rohn
Johann Rohn

Previous Sponsors

Benjamin Zecirovic
Benjamin Zecirovic
Ulric
Ulric
Fabian Jocks
Fabian Jocks

Contributors

Thanks to all the contributors who have helped make ZenStack better!

Source

Docs

License

MIT