mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 04:27:21 +00:00
Merge pull request #324 from screenfluent/feat/sveltekit-adapter
feat: add SvelteKit adapter
This commit is contained in:
@@ -308,6 +308,11 @@ async function buildAdapters() {
|
||||
platform: "node",
|
||||
}),
|
||||
|
||||
tsup.build({
|
||||
...baseConfig("sveltekit"),
|
||||
platform: "node",
|
||||
}),
|
||||
|
||||
tsup.build({
|
||||
...baseConfig("node"),
|
||||
platform: "node",
|
||||
|
||||
@@ -253,6 +253,11 @@
|
||||
"import": "./dist/adapter/astro/index.js",
|
||||
"require": "./dist/adapter/astro/index.js"
|
||||
},
|
||||
"./adapter/sveltekit": {
|
||||
"types": "./dist/types/adapter/sveltekit/index.d.ts",
|
||||
"import": "./dist/adapter/sveltekit/index.js",
|
||||
"require": "./dist/adapter/sveltekit/index.js"
|
||||
},
|
||||
"./adapter/aws": {
|
||||
"types": "./dist/types/adapter/aws/index.d.ts",
|
||||
"import": "./dist/adapter/aws/index.js",
|
||||
@@ -280,6 +285,7 @@
|
||||
"adapter/react-router": ["./dist/types/adapter/react-router/index.d.ts"],
|
||||
"adapter/bun": ["./dist/types/adapter/bun/index.d.ts"],
|
||||
"adapter/node": ["./dist/types/adapter/node/index.d.ts"],
|
||||
"adapter/sveltekit": ["./dist/types/adapter/sveltekit/index.d.ts"],
|
||||
"adapter/sqlite": ["./dist/types/adapter/sqlite/edge.d.ts"]
|
||||
}
|
||||
},
|
||||
@@ -309,6 +315,8 @@
|
||||
"remix",
|
||||
"react-router",
|
||||
"astro",
|
||||
"sveltekit",
|
||||
"svelte",
|
||||
"bun",
|
||||
"node"
|
||||
]
|
||||
|
||||
1
app/src/adapter/sveltekit/index.ts
Normal file
1
app/src/adapter/sveltekit/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./sveltekit.adapter";
|
||||
15
app/src/adapter/sveltekit/sveltekit.adapter.spec.ts
Normal file
15
app/src/adapter/sveltekit/sveltekit.adapter.spec.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { afterAll, beforeAll, describe } from "bun:test";
|
||||
import * as sveltekit from "./sveltekit.adapter";
|
||||
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
||||
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||
import { bunTestRunner } from "adapter/bun/test";
|
||||
|
||||
beforeAll(disableConsoleLog);
|
||||
afterAll(enableConsoleLog);
|
||||
|
||||
describe("sveltekit adapter", () => {
|
||||
adapterTestSuite(bunTestRunner, {
|
||||
makeApp: (c, a) => sveltekit.getApp(c, a ?? ({} as any)),
|
||||
makeHandler: (c, a) => (request: Request) => sveltekit.serve(c, a ?? ({} as any))({ request }),
|
||||
});
|
||||
});
|
||||
33
app/src/adapter/sveltekit/sveltekit.adapter.ts
Normal file
33
app/src/adapter/sveltekit/sveltekit.adapter.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
|
||||
|
||||
type TSvelteKit = {
|
||||
request: Request;
|
||||
};
|
||||
|
||||
export type SvelteKitBkndConfig<Env> = Pick<RuntimeBkndConfig<Env>, "adminOptions">;
|
||||
|
||||
/**
|
||||
* Get bknd app instance
|
||||
* @param config - bknd configuration
|
||||
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
|
||||
*/
|
||||
export async function getApp<Env>(
|
||||
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
|
||||
args: Env,
|
||||
) {
|
||||
return await createRuntimeApp(config, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create request handler for hooks.server.ts
|
||||
* @param config - bknd configuration
|
||||
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
|
||||
*/
|
||||
export function serve<Env>(
|
||||
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
|
||||
args: Env,
|
||||
) {
|
||||
return async (fnArgs: TSvelteKit) => {
|
||||
return (await getApp(config, args)).fetch(fnArgs.request);
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"pages": ["nextjs", "react-router", "astro", "vite"]
|
||||
"pages": ["nextjs", "react-router", "astro", "sveltekit", "vite"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
---
|
||||
title: "SvelteKit"
|
||||
description: "Run bknd inside SvelteKit"
|
||||
tags: ["documentation"]
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
To get started with SvelteKit and bknd, create a new SvelteKit project by following the [official guide](https://svelte.dev/docs/kit/creating-a-project), and then install bknd as a dependency:
|
||||
|
||||
<Tabs groupId='package-manager' persist items={[ 'npm', 'pnpm', 'yarn', 'bun']}>
|
||||
|
||||
```bash tab="npm"
|
||||
npm install bknd
|
||||
```
|
||||
|
||||
```bash tab="pnpm"
|
||||
pnpm install bknd
|
||||
```
|
||||
|
||||
```bash tab="yarn"
|
||||
yarn add bknd
|
||||
```
|
||||
|
||||
```bash tab="bun"
|
||||
bun add bknd
|
||||
```
|
||||
|
||||
</Tabs>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Callout type="warning">
|
||||
When run with Node.js, a version of 22 (LTS) or higher is required. Please
|
||||
verify your version by running `node -v`, and
|
||||
[upgrade](https://nodejs.org/en/download/) if necessary.
|
||||
</Callout>
|
||||
|
||||
Now create a `bknd.config.ts` file in the root of your project:
|
||||
|
||||
```typescript title="bknd.config.ts"
|
||||
import type { SvelteKitBkndConfig } from "bknd/adapter/sveltekit";
|
||||
|
||||
export default {
|
||||
connection: {
|
||||
url: "file:data.db",
|
||||
},
|
||||
} satisfies SvelteKitBkndConfig;
|
||||
```
|
||||
|
||||
See [bknd.config.ts](/extending/config) for more information on how to configure bknd. The `SvelteKitBkndConfig` type extends the base config type with the following properties:
|
||||
|
||||
```typescript
|
||||
export type SvelteKitBkndConfig<Env> = Pick<RuntimeBkndConfig<Env>, "adminOptions">;
|
||||
```
|
||||
|
||||
## Serve the API
|
||||
|
||||
The SvelteKit adapter uses SvelteKit's hooks mechanism to handle API requests. Create a `src/hooks.server.ts` file:
|
||||
|
||||
```typescript title="src/hooks.server.ts"
|
||||
import type { Handle } from "@sveltejs/kit";
|
||||
import { serve } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../bknd.config";
|
||||
|
||||
const bkndHandler = serve(config, env);
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
// handle bknd API requests
|
||||
const pathname = event.url.pathname;
|
||||
if (pathname.startsWith("/api/")) {
|
||||
const res = await bkndHandler(event);
|
||||
if (res.status !== 404) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
return resolve(event);
|
||||
};
|
||||
```
|
||||
|
||||
For more information about the connection object, refer to the [Database](/usage/database) guide.
|
||||
|
||||
<Callout type="info">
|
||||
The adapter uses `$env/dynamic/private` to access environment variables, making it runtime-agnostic
|
||||
and compatible with any deployment target (Node.js, Bun, Cloudflare, etc.).
|
||||
</Callout>
|
||||
|
||||
## Enabling the Admin UI
|
||||
|
||||
The SvelteKit adapter supports serving the Admin UI statically. First, copy the required assets to your `static` folder by adding a postinstall script to your `package.json`:
|
||||
|
||||
```json title="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"postinstall": "bknd copy-assets --out static" // [!code highlight]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then update your `bknd.config.ts` to configure the admin base path:
|
||||
|
||||
```typescript title="bknd.config.ts"
|
||||
import type { SvelteKitBkndConfig } from "bknd/adapter/sveltekit";
|
||||
|
||||
export default {
|
||||
connection: {
|
||||
url: "file:data.db",
|
||||
},
|
||||
adminOptions: { // [!code highlight]
|
||||
adminBasepath: "/admin" // [!code highlight]
|
||||
}, // [!code highlight]
|
||||
} satisfies SvelteKitBkndConfig;
|
||||
```
|
||||
|
||||
Finally, update your `hooks.server.ts` to also handle admin routes:
|
||||
|
||||
```typescript title="src/hooks.server.ts"
|
||||
import type { Handle } from "@sveltejs/kit";
|
||||
import { serve } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../bknd.config";
|
||||
|
||||
const bkndHandler = serve(config, env);
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
// handle bknd API and admin requests
|
||||
const pathname = event.url.pathname;
|
||||
if (pathname.startsWith("/api/") || pathname.startsWith("/admin")) { // [!code highlight]
|
||||
const res = await bkndHandler(event);
|
||||
if (res.status !== 404) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
return resolve(event);
|
||||
};
|
||||
```
|
||||
|
||||
## Example usage of the API
|
||||
|
||||
You can use the `getApp` function to access the bknd API in your server-side load functions:
|
||||
|
||||
```typescript title="src/routes/+page.server.ts"
|
||||
import type { PageServerLoad } from "./$types";
|
||||
import { getApp } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../../bknd.config";
|
||||
|
||||
export const load: PageServerLoad = async () => {
|
||||
const app = await getApp(config, env);
|
||||
const api = app.getApi();
|
||||
|
||||
const todos = await api.data.readMany("todos");
|
||||
|
||||
return {
|
||||
todos: todos.data ?? [],
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Then display the data in your Svelte component:
|
||||
|
||||
```svelte title="src/routes/+page.svelte"
|
||||
<script lang="ts">
|
||||
import type { PageData } from "./$types";
|
||||
|
||||
let { data }: { data: PageData } = $props();
|
||||
</script>
|
||||
|
||||
<h1>Todos</h1>
|
||||
<ul>
|
||||
{#each data.todos as todo (todo.id)}
|
||||
<li>{todo.title}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
```
|
||||
|
||||
### Using authentication
|
||||
|
||||
To use authentication in your load functions, pass the request headers to the API:
|
||||
|
||||
```typescript title="src/routes/+page.server.ts"
|
||||
import type { PageServerLoad } from "./$types";
|
||||
import { getApp } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../../bknd.config";
|
||||
|
||||
export const load: PageServerLoad = async ({ request }) => {
|
||||
const app = await getApp(config, env);
|
||||
const api = app.getApi({ headers: request.headers });
|
||||
await api.verifyAuth();
|
||||
|
||||
const todos = await api.data.readMany("todos");
|
||||
|
||||
return {
|
||||
todos: todos.data ?? [],
|
||||
user: api.getUser(),
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Check the [SvelteKit repository example](https://github.com/bknd-io/bknd/tree/main/examples/sveltekit) for more implementation details.
|
||||
@@ -27,6 +27,12 @@ bknd seamlessly integrates with popular frameworks, allowing you to use what you
|
||||
href="/integration/astro"
|
||||
/>
|
||||
|
||||
<Card
|
||||
icon={<Icon icon="simple-icons:svelte" className="text-fd-primary !size-6" />}
|
||||
title="SvelteKit"
|
||||
href="/integration/sveltekit"
|
||||
/>
|
||||
|
||||
<Card title="Yours missing?" href="https://github.com/bknd-io/bknd/issues/new">
|
||||
Create a new issue to request a guide for your framework.
|
||||
</Card>
|
||||
|
||||
@@ -103,6 +103,12 @@ Start by using the integration guide for these popular frameworks/runtimes. Ther
|
||||
href="/integration/deno"
|
||||
/>
|
||||
|
||||
<Card
|
||||
icon={<Icon icon="simple-icons:svelte" className="text-fd-primary !size-6" />}
|
||||
title="SvelteKit"
|
||||
href="/integration/sveltekit"
|
||||
/>
|
||||
|
||||
<Card
|
||||
icon={<Icon icon="tabler:lambda" className="text-fd-primary !size-6" />}
|
||||
title="AWS Lambda"
|
||||
|
||||
13
examples/sveltekit/.gitignore
vendored
Normal file
13
examples/sveltekit/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
/build
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
*.db
|
||||
static/manifest.json
|
||||
static/assets
|
||||
26
examples/sveltekit/README.md
Normal file
26
examples/sveltekit/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# bknd + SvelteKit Example
|
||||
|
||||
This example shows how to integrate bknd with SvelteKit.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
1. **`bknd.config.ts`** - bknd configuration with database connection, schema, and seed data
|
||||
2. **`src/hooks.server.ts`** - Routes `/api/*` requests to bknd
|
||||
3. **`src/routes/+page.server.ts`** - Uses `getApp()` to fetch data server-side
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /api/data/entity/todos` - List todos (requires auth)
|
||||
- `POST /api/auth/password/login` - Login
|
||||
|
||||
## Test Credentials
|
||||
|
||||
- Email: `admin@example.com`
|
||||
- Password: `password`
|
||||
56
examples/sveltekit/bknd.config.ts
Normal file
56
examples/sveltekit/bknd.config.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import type { SvelteKitBkndConfig } from "bknd/adapter/sveltekit";
|
||||
import { em, entity, text, libsql } from "bknd";
|
||||
import { createClient } from "@libsql/client";
|
||||
|
||||
const schema = em({
|
||||
todos: entity("todos", {
|
||||
title: text().required(),
|
||||
done: text(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default {
|
||||
connection: libsql(
|
||||
createClient({
|
||||
url: "file:data.db",
|
||||
})
|
||||
),
|
||||
config: {
|
||||
data: schema.toJSON(),
|
||||
auth: {
|
||||
enabled: true,
|
||||
allow_register: true,
|
||||
jwt: {
|
||||
issuer: "bknd-sveltekit-example",
|
||||
secret: "dev-secret-change-in-production-1234567890abcdef",
|
||||
},
|
||||
roles: {
|
||||
admin: {
|
||||
implicit_allow: true,
|
||||
},
|
||||
default: {
|
||||
permissions: ["data.entity.read", "data.entity.create"],
|
||||
is_default: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
adminOptions: {
|
||||
// this path must be the same as in `hooks.server.ts`
|
||||
adminBasepath: "/admin"
|
||||
},
|
||||
options: {
|
||||
seed: async (ctx) => {
|
||||
await ctx.app.module.auth.createUser({
|
||||
email: "admin@example.com",
|
||||
password: "password",
|
||||
role: "admin",
|
||||
});
|
||||
|
||||
await ctx.em.mutator("todos").insertMany([
|
||||
{ title: "Learn bknd", done: "true" },
|
||||
{ title: "Build with SvelteKit", done: "false" },
|
||||
]);
|
||||
},
|
||||
},
|
||||
} as const satisfies SvelteKitBkndConfig;
|
||||
24
examples/sveltekit/package.json
Normal file
24
examples/sveltekit/package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "bknd-sveltekit-example",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"postinstall": "node node_modules/.bin/bknd copy-assets --out static"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-auto": "^7.0.0",
|
||||
"@sveltejs/kit": "^2.0.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.0.0",
|
||||
"svelte": "^5.0.0",
|
||||
"typescript": "^5.0.0",
|
||||
"vite": "^7.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"bknd": "file:../../app",
|
||||
"@libsql/client": "^0.15.0"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
12
examples/sveltekit/src/app.html
Normal file
12
examples/sveltekit/src/app.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
19
examples/sveltekit/src/hooks.server.ts
Normal file
19
examples/sveltekit/src/hooks.server.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Handle } from "@sveltejs/kit";
|
||||
import { serve } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../bknd.config";
|
||||
|
||||
const bkndHandler = serve(config, env);
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
// Handle bknd API requests
|
||||
const pathname = event.url.pathname;
|
||||
if (pathname.startsWith("/api/") || pathname.startsWith("/admin")) {
|
||||
const res = await bkndHandler(event);
|
||||
if (res.status !== 404) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
return resolve(event);
|
||||
};
|
||||
15
examples/sveltekit/src/routes/+page.server.ts
Normal file
15
examples/sveltekit/src/routes/+page.server.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { PageServerLoad } from "./$types";
|
||||
import { getApp } from "bknd/adapter/sveltekit";
|
||||
import { env } from "$env/dynamic/private";
|
||||
import config from "../../bknd.config";
|
||||
|
||||
export const load: PageServerLoad = async () => {
|
||||
const app = await getApp(config, env);
|
||||
const api = app.getApi();
|
||||
|
||||
const todos = await api.data.readMany("todos");
|
||||
|
||||
return {
|
||||
todos: todos.data ?? [],
|
||||
};
|
||||
};
|
||||
24
examples/sveltekit/src/routes/+page.svelte
Normal file
24
examples/sveltekit/src/routes/+page.svelte
Normal file
@@ -0,0 +1,24 @@
|
||||
<script lang="ts">
|
||||
import type { PageData } from "./$types";
|
||||
|
||||
let { data }: { data: PageData } = $props();
|
||||
</script>
|
||||
|
||||
<h1>bknd + SvelteKit Example</h1>
|
||||
|
||||
<h2>Todos</h2>
|
||||
<ul>
|
||||
{#each data.todos as todo (todo.id)}
|
||||
<li>{todo.title} - {todo.done === "true" ? "Done" : "Pending"}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<h2>API Endpoints</h2>
|
||||
<ul>
|
||||
<li><a href="/api/data/entity/todos">/api/data/entity/todos</a></li>
|
||||
<li><a href="/api/auth/password/login">/api/auth/password/login</a> (POST)</li>
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
Login credentials: <code>admin@example.com</code> / <code>password</code>
|
||||
</p>
|
||||
BIN
examples/sveltekit/static/favicon.ico
Normal file
BIN
examples/sveltekit/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
3
examples/sveltekit/static/robots.txt
Normal file
3
examples/sveltekit/static/robots.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# allow crawling everything by default
|
||||
User-agent: *
|
||||
Disallow:
|
||||
12
examples/sveltekit/svelte.config.js
Normal file
12
examples/sveltekit/svelte.config.js
Normal file
@@ -0,0 +1,12 @@
|
||||
import adapter from "@sveltejs/adapter-auto";
|
||||
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
preprocess: vitePreprocess(),
|
||||
kit: {
|
||||
adapter: adapter(),
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
14
examples/sveltekit/tsconfig.json
Normal file
14
examples/sveltekit/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
}
|
||||
6
examples/sveltekit/vite.config.ts
Normal file
6
examples/sveltekit/vite.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { sveltekit } from "@sveltejs/kit/vite";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()],
|
||||
});
|
||||
Reference in New Issue
Block a user