|
| 1 | +--- |
| 2 | +title: TanStack Start |
| 3 | +description: Adapter for integrating with TanStack Start |
| 4 | +sidebar_position: 9 |
| 5 | +--- |
| 6 | + |
| 7 | +import ErrorHandling from './_error-handling.md'; |
| 8 | +import AdapterOptions from './_options.mdx'; |
| 9 | +import UsingAPI from './_using-api.mdx' |
| 10 | + |
| 11 | +# TanStack Start Adapter |
| 12 | + |
| 13 | +The `@zenstackhq/server/tanstack-start` module provides a quick way to install API routes onto a [TanStack Start](https://tanstack.com/start) project for database CRUD operations. Combined with ZenStack's power of enhancing Prisma with access policies, it's surprisingly simple to achieve a secure data backend without manually coding it. |
| 14 | + |
| 15 | +TanStack Start is a full-stack React framework powered by TanStack Router, offering full-document SSR, streaming, server functions, and bundling capabilities. |
| 16 | + |
| 17 | +### Installation |
| 18 | + |
| 19 | +```bash |
| 20 | +npm install @zenstackhq/server |
| 21 | +``` |
| 22 | + |
| 23 | +### Mounting the API |
| 24 | + |
| 25 | +You can use the `TanStackStartHandler` to create a handler for your API routes. TanStack Start uses file-based routing, so you'll typically create a catch-all route to handle all CRUD operations: |
| 26 | + |
| 27 | +```ts title='app/routes/api/$.ts' |
| 28 | +import { createFileRoute } from '@tanstack/react-router' |
| 29 | +import { TanStackStartHandler } from '@zenstackhq/server/tanstack-start' |
| 30 | +import { enhance } from '@zenstackhq/runtime' |
| 31 | +import { prisma } from '~/server/db' |
| 32 | + |
| 33 | +// create an enhanced Prisma client with user context |
| 34 | +function getPrisma() { |
| 35 | + // getSessionUser extracts the current session user from the request, its |
| 36 | + // implementation depends on your auth solution |
| 37 | + return enhance(prisma, { user: getSessionUser() }); |
| 38 | +} |
| 39 | + |
| 40 | +const handler = TanStackStartHandler({ |
| 41 | + getPrisma |
| 42 | +}) |
| 43 | + |
| 44 | +export const Route = createFileRoute('/api/$')({ |
| 45 | + server: { |
| 46 | + handlers: { |
| 47 | + GET: handler, |
| 48 | + POST: handler, |
| 49 | + PUT: handler, |
| 50 | + PATCH: handler, |
| 51 | + DELETE: handler, |
| 52 | + } |
| 53 | + } |
| 54 | +}) |
| 55 | +``` |
| 56 | + |
| 57 | +The TanStack Start handler takes the following options to initialize: |
| 58 | + |
| 59 | +<AdapterOptions getPrisma='() => unknown | Promise<unknown>' /> |
| 60 | + |
| 61 | +### Using the API |
| 62 | + |
| 63 | +<UsingAPI /> |
| 64 | + |
| 65 | +<ErrorHandling /> |
| 66 | + |
0 commit comments