SvelteKit Server Adapter
The @zenstackhq/server/sveltekit module provides a quick way to install a full set of CRUD API onto SvelteKit apps. Combined with ZenStack's powerful access policies, you can achieve a secure data backend without manually coding it.
Installation​
- npm
- pnpm
- bun
- yarn
npm install @zenstackhq/server
pnpm add @zenstackhq/server
bun add @zenstackhq/server
yarn add @zenstackhq/server
Mounting the API​
You can mount the API by creating SvelteKit server hooks like:
import { SvelteKitHandler } from '@zenstackhq/server/sveltekit';
import { RPCApiHandler } from '@zenstackhq/server/api';
import { getSessionUser } from '~/auth';
import { client } from '~/db';
import { schema } from '~/zenstack/schema';
export const handle = SvelteKitHandler({
apiHandler: new RPCApiHandler({ schema }),
prefix: '/api/model',
// getSessionUser extracts the current session user from the request, its
// implementation depends on your auth solution
getClient: (event) => client.$setAuth(getSessionUser(event)),
});
You can use the sequence helper to compose multiple server hooks.
The SvelteKit hooks handler takes the following options to initialize:
-
prefix
string
Prefix for the mounted API endpoints. E.g.: /api/model.
-
getClient (required)
(event: RequestEvent) => ClientContract<Schema> | Promise<ClientContract<Schema>>
A callback for getting a ZenStackClient instance for talking to the database. Usually you'll return a client instance with access policy enabled and user identity bound.
-
apiHandler (required)
ApiHandler
The API handler instance that determines the API specification.
Error Handling​
Refer to the specific sections for RPC Handler and RESTful Handler.