### Install bknd CLI Starter for React Router Source: https://docs.bknd.io/integration/react-router Use the CLI starter to create a new React Router project with bknd pre-integrated. This is the quickest way to get started. ```bash npx bknd create -i react-router ``` -------------------------------- ### Basic Deno App Setup Source: https://docs.bknd.io/integration/deno A minimal Deno setup for bknd API usage. Ensure the connection URL is correctly configured. ```typescript import { createAdapterApp } from "npm:bknd/adapter"; const app = await createAdapterApp({ connection: { url: "file:data.db", }, }); export default { fetch: app.fetch, }; ``` -------------------------------- ### Install bknd CLI Starter for Astro Source: https://docs.bknd.io/integration/astro Use the bknd CLI to create a new Astro project with bknd pre-integrated. ```bash npx bknd create -i astro ``` -------------------------------- ### Setup ClientProvider in React App Source: https://docs.bknd.io/usage/react Wrap your entire application with `ClientProvider` to make the bknd API instance available to all hooks. This is a mandatory setup step. ```javascript import { ClientProvider } from "bknd/client"; export default function App() { return {/* your app */}; } ``` -------------------------------- ### Install bknd CLI Starter for Cloudflare Source: https://docs.bknd.io/integration/cloudflare Use the bknd CLI to create a new Cloudflare starter project. ```bash npx bknd create -i cloudflare ``` -------------------------------- ### Install SQLocal Package Source: https://docs.bknd.io/usage/database Install the sqlocal package to use bknd with sqlocal for offline experiences. ```bash npm install sqlocal ``` -------------------------------- ### Basic bknd.config.ts Example Source: https://docs.bknd.io/extending/config A minimal configuration file defining the database connection URL. ```typescript import type { BkndConfig } from "bknd/adapter"; export default { connection: { url: "file:data.db", }, } satisfies BkndConfig; ``` -------------------------------- ### Advanced bknd.config.ts with Plugins and Routes Source: https://docs.bknd.io/extending/config An example demonstrating database connection, plugin registration, and custom routes using Hono and Kysely. ```typescript import type { BkndConfig } from "bknd/adapter"; import { showRoutes } from "bknd/plugins"; export default { connection: { url: process.env.DB_URL ?? "file:data.db", }, onBuilt: async (app) => { // `app.server` is a Hono instance const hono = app.server; hono.get("/hello", (c) => c.text("Hello World")); // for complex queries, you can use Kysely directly const db = app.connection.kysely; hono.get("/custom_query", async (c) => { return c.json(await db.selectFrom("pages").selectAll().execute()); }); }, options: { plugins: [showRoutes()], }, } satisfies BkndConfig; ``` -------------------------------- ### bknd.config.ts example Source: https://docs.bknd.io/usage/cli Example configuration file for bknd. This file can specify database connection details. The `app` function allows access to environment variables, useful in environments like Cloudflare Workers. ```typescript import type { BkndConfig } from "bknd/adapter"; export default { // you can either specify the connection directly connection: { url: "file:data.db", }, // or use the `app` function which passes the environment variables app: (env) => ({ connection: { url: env.DB_URL, }, }), } satisfies BkndConfig; ``` -------------------------------- ### Full Stack (Embedded Mode) Setup Source: https://docs.bknd.io/usage/react This example demonstrates how to set up Bknd in an embedded mode within a React application, suitable for frameworks like Next.js or Astro. It covers server-side user extraction and client-side component rendering with authentication. ```APIDOC ## Full Stack (Embedded Mode) Use this pattern when bknd is embedded in your framework (e.g., Next.js, Astro, React Router). The backend and frontend run in the same process. ```javascript // this example is not specific to any framework, but you can use it with any framework that supports server-side rendering import { ClientProvider, useAuth } from "bknd/client"; import { useEffect } from "react"; // setup: extract user from server-side // in your server-side code (e.g., Next.js loader, Astro endpoint): export async function loader({ request }) { // create API instance from your app (may be available in context) const api = app.getApi({ request }); // extracts credentials from request // or: const api = app.getApi({ headers: request.headers }); const user = api.getUser(); // optionally: await api.verifyAuth(); return { user }; } // in your component: export default function App({ user }) { return ( ); } function InnerApp() { const auth = useAuth(); // optionally verify if not already verified useEffect(() => { if (!auth.verified) { auth.verify(); } }, []); if (auth.user) { return (

Logged in as {auth.user.email}

{/* logout by navigating to the logout endpoint */} Logout
); } // use form-based authentication for full-stack apps return (
); } ``` **Notes:** * No `baseUrl` needed in `ClientProvider` - it automatically uses the same origin * Pass the `user` prop from server-side to avoid an initial unauthenticated state * Use `app.getApi({ request })` or `app.getApi({ headers })` on the server to extract credentials * The logout endpoint (`/api/auth/logout`) clears the session and redirects back * Authentication persists via cookies automatically handled by the framework ``` -------------------------------- ### Get and write app configuration Source: https://docs.bknd.io/usage/cli Run this command to retrieve your application's configuration and save it to a specified file. ```bash npx bknd config --out appconfig.json ``` -------------------------------- ### Run Node.js Server Source: https://docs.bknd.io/integration/node Execute your Node.js server file to start the bknd application. ```bash node server.js ``` -------------------------------- ### Install bknd with bun Source: https://docs.bknd.io/integration/node Install the bknd package as a dependency in your Node.js project using bun. ```bash bun add bknd ``` -------------------------------- ### Run bknd Instance with CLI Source: https://docs.bknd.io/extending/config Use the `bknd run` command in your project's root directory to start an instance of your bknd application. ```bash npx bknd run ``` -------------------------------- ### Run bknd CLI Source: https://docs.bknd.io/usage/cli Execute the bknd CLI to start a bknd instance. Use `npx bknd --help` for a list of all available commands. ```bash npx bknd ``` -------------------------------- ### Serve bknd API in Tanstack Start Source: https://docs.bknd.io/integration/tanstack-start Create an API route handler in Tanstack Start to serve bknd API requests using the `serve` function. ```typescript import { createFileRoute } from "@tanstack/react-router"; import config from "../../bknd.config"; import { serve } from "bknd/adapter/tanstack-start"; const handler = serve(config); export const Route = createFileRoute("/api/$")({ server: { handlers: { ANY: async ({ request }) => await handler(request), }, }, }); ``` -------------------------------- ### Docker Compose Example Source: https://docs.bknd.io/integration/docker A basic Docker Compose configuration to build and run the bknd service directly from the git repository. ```yaml services: bknd: pull_policy: build build: https://github.com/bknd-io/bknd.git#main:docker ports: - 1337:1337 environment: ARGS: "--db-url file:/data/data.db" volumes: - ${DATA_DIR:-.}/data:/data ``` -------------------------------- ### Basic bknd Configuration for SvelteKit Source: https://docs.bknd.io/integration/sveltekit Configure bknd connection settings in `bknd.config.ts`. This example sets up a file-based database connection. ```typescript import type { SvelteKitBkndConfig } from "bknd/adapter/sveltekit"; export default { connection: { url: "file:data.db", }, } satisfies SvelteKitBkndConfig; ``` -------------------------------- ### Run bknd with Turso/LibSQL database Source: https://docs.bknd.io/usage/cli Start a bknd instance connected to a Turso/LibSQL database. Provide the database URL and an optional token if the database is protected. ```bash npx bknd run --db-url libsql://your-db.turso.io --db-token ``` -------------------------------- ### Install bknd with yarn Source: https://docs.bknd.io/integration/node Install the bknd package as a dependency in your Node.js project using yarn. ```bash yarn add bknd ``` -------------------------------- ### Install bknd with pnpm Source: https://docs.bknd.io/integration/node Install the bknd package as a dependency in your Node.js project using pnpm. ```bash pnpm install bknd ``` -------------------------------- ### Install bknd with npm Source: https://docs.bknd.io/integration/node Install the bknd package as a dependency in your Node.js project using npm. ```bash npm install bknd ``` -------------------------------- ### ClientProvider Setup Source: https://docs.bknd.io/usage/react Wrap your application with ClientProvider to make bknd API instance available to all hooks. It accepts baseUrl and other API options. ```APIDOC ## Setup In order to use the React hooks, make sure you wrap your `` inside ``. This provides the bknd API instance to all hooks in your component tree: ```jsx import { ClientProvider } from "bknd/client"; export default function App() { return {/* your app */}; } ``` ### ClientProvider Props The `ClientProvider` accepts the following props: Prop| Type| Default ---|---|--- `baseUrl?`| `string`| - `children?`| `ReactNode`| - All Api options are also supported and will be passed to the internal API instance. Common options include: Prop| Type| Default ---|---|--- `token?`| `string`| - `storage?`| `{ getItem, setItem, removeItem }`| - `onAuthStateChange?`| `(state: AuthState) => void`| - `fetcher?`| `(input: RequestInfo, init?: RequestInit) => Promise`| - `credentials?`| `"include" | "omit" | "same-origin"`| - ### Usage Examples **Using with a remote bknd instance:** ```jsx import { ClientProvider } from "bknd/client"; export default function App() { return ( {/* your app */} ); } ``` **Using with an embedded bknd instance (same origin):** ```jsx import { ClientProvider } from "bknd/client"; export default function App() { // no baseUrl needed - will use window.location.origin return {/* your app */}; } ``` **Using with custom authentication:** ```jsx import { ClientProvider } from "bknd/client"; export default function App() { return ( { console.log("Auth state changed:", state); }} > {/* your app */} ); } ``` ``` -------------------------------- ### Example generated types file Source: https://docs.bknd.io/usage/cli This is an example of the `bknd-types.d.ts` file generated by the `bknd types` command, including type definitions for database entities. ```typescript import type { DB } from "bknd"; import type { Insertable, Selectable, Updateable, Generated } from "kysely"; declare global { type BkndEntity = Selectable; type BkndEntityCreate = Insertable; type BkndEntityUpdate = Updateable; } export interface Todos { id: Generated; title?: string; done?: boolean; } interface Database { todos: Todos; } declare module "bknd" { interface DB extends Database {} } ``` -------------------------------- ### Configure bknd for Tanstack Start Source: https://docs.bknd.io/integration/tanstack-start Set up the bknd configuration file (`bknd.config.ts`) with database connection, schema, authentication, and seeding options. ```typescript import { type TanstackStartConfig } from "bknd/adapter/tanstack-start"; import { em, entity, text, boolean } from "bknd"; const schema = em({ todos: entity("todos", { title: text(), done: boolean(), }), }); export default { connection: { url: "file:data.db", }, config: { data: schema.toJSON(), auth: { enabled: true, jwt: { secret: "random_gibberish_please_change-this", // use something like `openssl rand -hex 32` for production }, }, }, options: { // the seed option is only executed if the database was empty seed: async (ctx) => { // create some entries await ctx.em.mutator("todos").insertMany([ { title: "Learn bknd", done: true }, { title: "Build something cool", done: false }, ]); // and create a user await ctx.app.module.auth.createUser({ email: "test@bknd.io", password: "12345678", }); }, }, } satisfies TanstackStartConfig; ``` -------------------------------- ### Configure syncSecrets Plugin Source: https://docs.bknd.io/extending/plugins Enable and configure the built-in `syncSecrets` plugin to write app secrets to a file on boot and build. This example shows writing an example .env file. Ensure this is disabled in production. ```typescript import { syncSecrets } from "bknd/plugins"; import { writeFile } from "node:fs/promises"; export default { options: { plugins: [ syncSecrets({ // whether to enable the plugin, make sure to disable in production enabled: true, // your writing function (required) write: async (secrets) => { // apply your writing logic, e.g. writing a template file in an env format await writeFile( ".env.example", Object.entries(secrets) .map(([key]) => `${key}=`) .join("\n") ); }, }), ] }, } satisfies BkndConfig; ``` -------------------------------- ### Run bknd Instance with CLI Source: https://docs.bknd.io/ Spin up a local bknd instance using the bknd CLI. This command creates a `data.db` SQLite database and starts the web server at http://localhost:1337. ```bash npx bknd run ``` ```bash bunx bknd run ``` -------------------------------- ### Run bknd with in-memory database Source: https://docs.bknd.io/usage/cli Start a bknd instance using an ephemeral in-memory database. Note that data will not be persisted and will be lost when the process terminates. ```bash npx bknd run --memory ``` -------------------------------- ### Get default configuration template Source: https://docs.bknd.io/usage/cli Use this command to retrieve a template configuration, which can be useful for setting up a new project. ```bash npx bknd config --default ``` -------------------------------- ### Connect to PostgreSQL with Xata Client Source: https://docs.bknd.io/usage/database Example of connecting to PostgreSQL using the '@xata.io/client'. Requires building a Xata client and using XataDialect from '@xata.io/kysely'. ```typescript import { createCustomPostgresConnection } from "bknd"; import { XataDialect } from "@xata.io/kysely"; import { buildClient } from "@xata.io/client"; const client = buildClient(); const xata = new client({ databaseURL: process.env.XATA_URL, apiKey: process.env.XATA_API_KEY, branch: process.env.XATA_BRANCH, }); const xataConnection = createCustomPostgresConnection("xata", XataDialect, { supports: { batching: false, }, }); serve({ connection: xataConnection({ xata }), }); ``` -------------------------------- ### Connect to PostgreSQL with Neon Serverless Source: https://docs.bknd.io/usage/database Example of connecting to PostgreSQL using the '@neondatabase/serverless' client. Requires a NeonDialect from 'kysely-neon'. ```typescript import { createCustomPostgresConnection } from "bknd"; import { NeonDialect } from "kysely-neon"; const neon = createCustomPostgresConnection("neon", NeonDialect); serve({ connection: neon({ connectionString: process.env.NEON, }), }); ``` -------------------------------- ### Helper to Instantiate bknd and Get API Source: https://docs.bknd.io/integration/react-router Create a helper file (`app/bknd.ts`) to instantiate the bknd instance and retrieve the API. This simplifies usage across your application. ```typescript import { type ReactRouterBkndConfig, getApp as getBkndApp, } from "bknd/adapter/react-router"; import config from "../bknd.config"; export { config }; // you may adjust this function depending on your runtime environment. // e.g. when deploying to cloudflare workers, you'd want the FunctionArgs to be passed in // to resolve environment variables export async function getApp() { return await getBkndApp(config, process.env as any); } export async function getApi( args?: { request: Request }, opts?: { verify?: boolean }, ) { const app = await getApp(); if (opts?.verify) { const api = app.getApi({ headers: args?.request.headers }); await api.verifyAuth(); return api; } return app.getApi(); } ``` -------------------------------- ### Docker Compose Example with Version and Labels Source: https://docs.bknd.io/integration/docker An extended Docker Compose configuration to build a specific bknd version from the git repository, including build arguments and labels for image identification. ```yaml services: bknd: pull_policy: build build: context: https://github.com/bknd-io/bknd.git#main:docker args: VERSION: labels: - x-bknd-version= ports: - 1337:1337 environment: ARGS: "--db-url file:/data/data.db" volumes: - ${DATA_DIR:-.}/data:/data ``` -------------------------------- ### Run bknd with file-based database Source: https://docs.bknd.io/usage/cli Start a bknd instance using a file-based database. The database file will be created in the current directory if it doesn't exist. You can specify a custom path using `--db-url`. ```bash npx bknd run --db-url file:data.db ``` -------------------------------- ### Configure bknd for React Router Source: https://docs.bknd.io/integration/react-router Create a `bknd.config.ts` file in your project root to configure bknd. This example sets up a file-based database connection. ```typescript import type { ReactRouterBkndConfig } from "bknd/adapter/react-router"; export default { connection: { url: "file:data.db", }, } satisfies ReactRouterBkndConfig; ``` -------------------------------- ### Serve bknd API in Next.js Source: https://docs.bknd.io/integration/nextjs Create a helper file `src/bknd.ts` to instantiate the bknd instance and retrieve the API, importing configuration from `bknd.config.ts`. This setup allows for API verification. ```typescript import { type NextjsBkndConfig, getApp as getBkndApp, } from "bknd/adapter/nextjs"; import { headers } from "next/headers"; import config from "../bknd.config"; export { config }; export async function getApp() { return await getBkndApp(config, process.env); } export async function getApi(opts?: { verify?: boolean }) { const app = await getApp(); if (opts?.verify) { const api = app.getApi({ headers: await headers() }); await api.verifyAuth(); return api; } return app.getApi(); } ``` -------------------------------- ### Database Connection Options Source: https://docs.bknd.io/extending/config Examples of different ways to define the database connection, including default SQLite, Node.js SQLite, Bun SQLite, and LibSQL. ```typescript // uses the default SQLite connection depending on the runtime const connection = { url: "" }; ``` ```typescript // the same as above, but more explicit import { sqlite } from "bknd/adapter/sqlite"; const connection = sqlite({ url: "" }); ``` ```typescript // Node.js SQLite, default on Node.js import { nodeSqlite } from "bknd/adapter/node"; const connection = nodeSqlite({ url: "" }); ``` ```typescript // Bun SQLite, default on Bun import { bunSqlite } from "bknd/adapter/bun"; const connection = bunSqlite({ url: "" }); ``` ```typescript // LibSQL, default on Cloudflare import { libsql } from "bknd"; const connection = libsql({ url: "" }); ``` -------------------------------- ### Serve API and Static Files with Node Adapter Source: https://docs.bknd.io/integration/node Configure and start the bknd Node adapter to serve the API and static files. An in-memory database is used if no connection configuration is provided. ```typescript import { serve } from "bknd/adapter/node"; // if the configuration is omitted, it uses an in-memory database /** @type {import("bknd/adapter/node").NodeAdapterOptions} */ const config = { connection: { url: "file:data.db", }, }; serve(config); ``` -------------------------------- ### Get Default Configuration via CLI Source: https://docs.bknd.io/extending/config Use the CLI to retrieve the default configuration. The `--pretty` flag formats the output for better readability. ```bash npx bknd config --default --pretty ``` -------------------------------- ### Run bknd with TypeScript config Source: https://docs.bknd.io/usage/cli Start a bknd instance using a TypeScript configuration file. This requires Node.js with experimental strip types enabled or using `tsx`. ```bash node --experimental-strip-types node_modules/.bin/bknd run ``` ```bash npx tsx node_modules/.bin/bknd run ``` -------------------------------- ### Access bknd API in SvelteKit server load function Source: https://docs.bknd.io/integration/sveltekit Use `getApp` in `src/routes/+page.server.ts` to access the bknd API. This example fetches 'todos' data. ```typescript 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 ?? [], }; }; ``` -------------------------------- ### Display Last 10 Media Items with Media.Dropzone Source: https://docs.bknd.io/usage/elements Use Media.Dropzone to retrieve and upload media. This example shows how to fetch the last 10 items from your bknd instance. ```jsx import { Media } from "bknd/elements"; export default function MediaGallery() { return ; } ``` -------------------------------- ### UI-only Mode: Basic Configuration Source: https://docs.bknd.io/usage/setup Configure bknd with a database connection in UI-only mode. This is the default mode and requires no setup code beyond the database connection. ```typescript import type { BkndConfig } from "bknd"; export default { connection: { url: "file:data.db" }, } satisfies BkndConfig; ``` -------------------------------- ### Complete CRUD Example with useEntityQuery Source: https://docs.bknd.io/usage/react Demonstrates full CRUD operations for a 'todos' entity using the useEntityQuery hook. Includes fetching a list with query parameters, creating, updating checkboxes, and deleting todos. ```javascript import { useEntityQuery } from "bknd/client"; export default function TodoList() { const { data: todos, create, update, _delete, isLoading } = useEntityQuery( "todos", undefined, // no id, so we fetch a list { limit: 10, sort: "-id", // newest first } ); if (isLoading) return
Loading...
; return (
{ const title = formData.get("title") as string; await create({ title, done: false }); }}>
    {todos?.map((todo) => (
  • { await update({ done: !todo.done }, todo.id); }} /> {todo.title}
  • ))}
); } ``` -------------------------------- ### Show bknd run command help Source: https://docs.bknd.io/usage/cli Display detailed options for the `run` command, including port, memory, config, and database settings. Use this to understand how to customize instance startup. ```bash npx bknd run --help ``` -------------------------------- ### Serve bknd API requests in SvelteKit hooks Source: https://docs.bknd.io/integration/sveltekit Integrate bknd API handling into SvelteKit by creating a `src/hooks.server.ts` file. This setup routes requests starting with `/api/` to the bknd handler. ```typescript 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); }; ``` -------------------------------- ### Enable Admin UI in Tanstack Start Source: https://docs.bknd.io/integration/tanstack-start Create a client-side route for the Admin UI using bknd's `Admin` component and `useAuth` hook. Ensure `ssr: false` is set for this route. ```typescript import { createFileRoute } from "@tanstack/react-router"; import { useAuth } from "bknd/client"; import "bknd/dist/styles.css"; import { Admin } from "bknd/ui"; export const Route = createFileRoute("/admin/$")({ ssr: false, // "data-only" works too component: RouteComponent, }); function RouteComponent() { const { user } = useAuth(); return ( ); }; ``` -------------------------------- ### Query Example: Fetching Limited and Sorted Entities Source: https://docs.bknd.io/usage/react Shows how to fetch a paginated and sorted list of entities using `useEntityQuery` by providing query parameters for limit and sort order. Includes basic loading state handling. ```javascript import { useEntityQuery } from "bknd/client"; export default function TodoList() { const { data: todos, isLoading } = useEntityQuery("todos", undefined, { limit: 5, sort: "-id", // descending by id }); if (isLoading) return
Loading...
; return (
    {todos?.map((todo) => (
  • {todo.title}
  • ))}
); } ``` -------------------------------- ### Create Deno CLI Starter Project Source: https://docs.bknd.io/integration/deno Use this command to generate a new Deno CLI starter project with bknd. ```bash deno run npm:bknd create -i deno ``` -------------------------------- ### Serve bknd Admin UI with Vite Source: https://docs.bknd.io/integration/introduction Integrate the bknd Admin UI into your application using Vite. This example shows how to import and render the Admin component with provider. ```typescript import { Admin } from "bknd/ui"; import "bknd/dist/styles.css"; export default function AdminPage() { return ; } ``` -------------------------------- ### Create Bun CLI Starter Project Source: https://docs.bknd.io/integration/bun Use this command to quickly scaffold a new bknd project configured for Bun. ```bash npx bknd create -i bun ``` -------------------------------- ### User Authentication with createServerFn Source: https://docs.bknd.io/integration/tanstack-start Implement user authentication by passing request headers to the API using `createServerFn`. This example shows how to retrieve user information and handle login/logout links. ```typescript import { getApi } from "@/bknd"; import { createServerFn } from "@tanstack/react-start"; import { Link } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router"; import { getRequest } from "@tanstack/react-start/server"; export const getUser = createServerFn() .handler(async () => { const request = getRequest(); const api = await getApi({ verify: true, headers: request.headers }); const user = api.getUser(); return { user }; }); export const Route = createFileRoute("/user")({ component: RouteComponent, loader: async () => { return { user: await getUser() }; }, }); function RouteComponent() { const { user } = Route.useLoaderData(); return (
{user ? ( <> Logged in as {user.email}.{" "} Logout ) : (

Not logged in. Login

Sign in with: test@bknd.io / 12345678

)}
) } ``` -------------------------------- ### Customize Admin UI with React Source: https://docs.bknd.io/extending/admin This example demonstrates how to deeply customize the Admin UI by configuring entity-specific actions, headers, fields, and adding custom routes within a React application. It requires the 'bknd/ui' and 'wouter' libraries. ```javascript import { Admin } from "bknd/ui"; import { Route } from "wouter"; export function App() { return ( alert("custom"), }, ], }, entities: { // use any entity that is registered tests: { actions: (context, entity, data) => ({ primary: [ // this action is only rendered in the update context context === "update" && { children: "another", onClick: () => alert("another"), }, ], context: [ // this action is always rendered in the dropdown { label: "Custom", onClick: () => alert( "custom: " + JSON.stringify({ context, entity: entity.name, data }), ), }, ], }), // render a header for the entity header: (context, entity, data) =>
test header
, // override the rendering of the title field fields: { title: { render: (context, entity, field, ctx) => { return ( ctx.handleChange(e.target.value)} /> ); }, }, }, }, // system entities work too users: { header: () => { return
System entity
; }, }, }, }} > {/* You may also add custom routes, these always have precedence over the Admin routes */}
custom
); } ``` -------------------------------- ### Create Node CLI Starter Project Source: https://docs.bknd.io/integration/node Use the bknd CLI to quickly create a new Node.js project with bknd pre-configured. ```bash npx bknd create -i node ``` -------------------------------- ### Create bknd AWS Lambda CLI Starter Source: https://docs.bknd.io/integration/aws Use the CLI starter to create a new Bun project for AWS Lambda integration. ```bash npx bknd create -i aws ``` -------------------------------- ### Install Vite Dev Server Dependency Source: https://docs.bknd.io/integration/vite Install the necessary Vite dev server adapter for bknd. This dependency is required for Vite integration. ```bash npm install @hono/vite-dev-server ``` -------------------------------- ### Install bknd Manually for AWS Lambda Source: https://docs.bknd.io/integration/aws Install bknd as a dependency for your AWS Lambda project using npm, pnpm, yarn, or bun. ```bash npm install bknd ``` ```bash pnpm install bknd ``` ```bash yarn add bknd ``` ```bash bun add bknd ``` -------------------------------- ### Show help for config command Source: https://docs.bknd.io/usage/cli Execute this command to see all available options for the `config` command. ```bash $ npx bknd config --help Usage: bknd config [options] get app config Options: -c, --config config file --db-url database url, can be any valid sqlite url --pretty pretty print --default use default config --secrets include secrets in output --out output file -h, --help display help for command ``` -------------------------------- ### Deploy bknd Lambda using CLI Starter Source: https://docs.bknd.io/integration/aws Deploy the bknd Lambda function using the `deploy` script provided by the CLI starter. ```bash npm run deploy ``` -------------------------------- ### Serve API and Static Files with Bun Adapter Source: https://docs.bknd.io/integration/bun Use the `serve` function from the bknd Bun adapter to run your API and serve static files. Configuration can be omitted for an in-memory database. ```typescript import { serve } from "bknd/adapter/bun"; // if the configuration is omitted, it uses an in-memory database serve({ connection: { url: "file:data.db", }, }); ``` -------------------------------- ### config_server_get Source: https://docs.bknd.io/usage/mcp/tools-resources Get Server configuration ```APIDOC ## config_server_get ### Description Get Server configuration ### Parameters #### Query Parameters - **path?** (string) - Optional - The path to the server configuration. - **depth?** (number) - Optional - The depth of the server configuration to retrieve. - **secrets?** (boolean) - Optional - If true, includes secrets in the response. ``` -------------------------------- ### Retrieve a file as a stream Source: https://docs.bknd.io/usage/sdk Use the `getFile` method to get a file as a readable stream of Uint8Array. ```javascript const { data } = await api.media.getFile("image.jpg"); // ^? ReadableStream ``` -------------------------------- ### Configure Admin UI postinstall script Source: https://docs.bknd.io/integration/sveltekit Add a `postinstall` script to `package.json` to copy bknd Admin UI assets to the static folder. This ensures the UI is available for serving. ```json { "scripts": { "postinstall": "bknd copy-assets --out static" } } ``` -------------------------------- ### Show help for sync command Source: https://docs.bknd.io/usage/cli Execute this command to see all available options for the `sync` command, which is used for database synchronization. ```bash $ npx bknd sync --help Usage: bknd sync [options] sync database Options: -c, --config config file --db-url database url, can be any valid sqlite url --seed perform seeding operations --force perform database syncing operations --drop include destructive DDL operations --out output file --sql use sql output -h, --help display help for command ``` -------------------------------- ### Retrieve authentication strategies Source: https://docs.bknd.io/usage/sdk Use the `strategies` method to get a list of available authentication strategies. ```javascript const { data } = await api.auth.strategies(); ``` -------------------------------- ### Import and use generated types Source: https://docs.bknd.io/usage/cli Example of importing and using the generated database types in your TypeScript code. ```typescript import type { DB } from "bknd"; type Todo = DB["todos"]; ``` -------------------------------- ### Instantiate bknd App and API Source: https://docs.bknd.io/integration/tanstack-start Create a helper file to instantiate the bknd application and retrieve the API instance, optionally verifying authentication. ```typescript import config from "../bknd.config"; import { getApp } from "bknd/adapter/tanstack-start"; export async function getApi({ headers, verify, }: { verify?: boolean; headers?: Headers; }) { const app = await getApp(config, process.env); if (verify) { const api = app.getApi({ headers }); await api.verifyAuth(); return api; } return app.getApi(); }; ``` -------------------------------- ### Get a file stream directly Source: https://docs.bknd.io/usage/sdk Use `getFileStream` to obtain a direct readable stream of a file's content. ```javascript const stream = await api.media.getFileStream("image.jpg"); // ^? ReadableStream ``` -------------------------------- ### Configure Local Media Adapter for Development Source: https://docs.bknd.io/modules/media Set up the local file system adapter for development and testing in your bknd.config.ts file. This configuration stores uploaded files in a specified directory, making them accessible via your application's public path. ```typescript import { registerLocalMediaAdapter } from "bknd/adapter/node"; import type { BkndConfig } from "bknd/adapter"; // Register the local media adapter const local = registerLocalMediaAdapter(); export default { config: { media: { enabled: true, adapter: local({ path: "./public/uploads", // Files will be stored in this directory }), }, }, } satisfies BkndConfig; ``` -------------------------------- ### Create Vite Server Entry Point Source: https://docs.bknd.io/integration/vite Set up the server entry point for Vite to serve the bknd API. This file imports and exports the serve function with your configuration. ```typescript import { serve } from "bknd/adapter/vite"; import config from "./bknd.config"; export default serve(config); ``` -------------------------------- ### Serve Admin UI with `serveStaticViaImport` Source: https://docs.bknd.io/integration/deno Integrates bknd with Deno, serving the Admin UI directly from the bknd package using dynamic raw imports. Requires unstable `raw-imports`. ```typescript import { createRuntimeApp, serveStaticViaImport } from "bknd/adapter"; const app = await createRuntimeApp({ connection: { url: "file:data.db", }, serveStatic: serveStaticViaImport() }); export default { fetch: app.fetch, }; ``` -------------------------------- ### Count records matching criteria Source: https://docs.bknd.io/usage/sdk Use the `count` method to get the number of records in an entity that match specific criteria. ```javascript const { data } = await api.data.count("posts", { views: { $gt: 100 } }); ``` -------------------------------- ### Configure Admin UI base path in bknd.config.ts Source: https://docs.bknd.io/integration/sveltekit Update `bknd.config.ts` to specify the `adminBasepath` for the Admin UI. This example sets it to `/admin`. ```typescript import type { SvelteKitBkndConfig } from "bknd/adapter/sveltekit"; export default { connection: { url: "file:data.db", }, adminOptions: { adminBasepath: "/admin" }, } satisfies SvelteKitBkndConfig; ``` -------------------------------- ### Configure bknd with Astro Source: https://docs.bknd.io/integration/astro Set up the `bknd.config.ts` file in your project root with connection details. ```typescript import type { AstroBkndConfig } from "bknd/adapter/astro"; export default { connection: { url: "file:data.db", }, } satisfies AstroBkndConfig; ``` -------------------------------- ### Initialize API with Token Option Source: https://docs.bknd.io/usage/sdk Create an API instance with a specific token, such as an admin token, by providing both host and token options. ```typescript import { Api } from "bknd/client"; const api = new Api({ host: "https://", token: "", }); ``` -------------------------------- ### Use devFsWrite with bknd Plugins Source: https://docs.bknd.io/integration/cloudflare Utilize the `devFsWrite` function provided by the bknd Vite plugin to write files, for example, when using the `syncTypes` plugin. ```typescript import { devFsWrite } from "bknd/adapter/cloudflare"; import { syncTypes } from "bknd/plugins"; export default { options: { plugins: [ syncTypes({ write: async (et) => { await devFsWrite("bknd-types.d.ts", et.toString()); } }), ] }, } satisfies BkndConfig; ``` -------------------------------- ### Display fetched data in Svelte component Source: https://docs.bknd.io/integration/sveltekit Render the fetched 'todos' data in a Svelte component (`src/routes/+page.svelte`). This example iterates over the todos and displays their titles. ```svelte

Todos

    {#each data.todos as todo (todo.id)}
  • {todo.title}
  • {/each}
``` -------------------------------- ### Show help for types command Source: https://docs.bknd.io/usage/cli Execute this command to see all available options for the `types` command. ```bash $ npx bknd types --help Usage: bknd types [options] generate types Options: -o, --outfile output file (default: "bknd-types.d.ts") --no-write do not write to file -h, --help display help for command ``` -------------------------------- ### Create bknd API Instance Helper Source: https://docs.bknd.io/integration/astro Helper file `src/bknd.ts` to instantiate the bknd instance and retrieve the API, importing configuration. ```typescript import type { AstroGlobal } from "astro"; import { getApp as getBkndApp } from "bknd/adapter/astro"; import config from "../bknd.config"; export { config }; export async function getApp() { return await getBkndApp(config); } export async function getApi( astro: AstroGlobal, opts?: { mode: "static" } | { mode?: "dynamic"; verify?: boolean }, ) { const app = await getApp(); if (opts?.mode !== "static" && opts?.verify) { const api = app.getApi({ headers: astro.request.headers }); await api.verifyAuth(); return api; } return app.getApi(); } ``` -------------------------------- ### Authenticate MCP Server with Token Option Source: https://docs.bknd.io/usage/mcp/overview Start the MCP server on STDIO transport and provide an authentication token using the `--token` option. ```bash npx bknd mcp --token ``` -------------------------------- ### Configure LibSQL with Client Instance Source: https://docs.bknd.io/usage/database Configure LibSQL by passing a pre-created client instance. This is useful for file, in-memory, or embedded replica modes. ```typescript import { libsql, type BkndConfig } from "bknd"; import { createClient } from "@libsql/client"; const client = createClient({ url: "libsql://.turso.io", authToken: "", }); export default { connection: libsql(client), } satisfies BkndConfig; ``` -------------------------------- ### API 'select' parameter: Web standard vs. Handy alternative Source: https://docs.bknd.io/motivation Demonstrates two ways to use the 'select' search parameter for retrieving a list of entities. The first adheres to the web standard, while the second offers a more concise, handy alternative. ```http /api/data/todos?select=id&select=name # web standard ``` ```http /api/data/todos?select=id,name # handy alternative ``` -------------------------------- ### Show bknd CLI help Source: https://docs.bknd.io/usage/cli View the available commands and options for the bknd CLI. This command lists all functionalities provided by the CLI. ```bash npx bknd --help ``` -------------------------------- ### Get MCP Client from App Instance Source: https://docs.bknd.io/usage/mcp/overview Obtain the MCP client directly from your app instance using `getMcpClient`. This method avoids network travel. ```typescript import { createApp } from "bknd"; const app = createApp(); const client = app.getMcpClient(); ``` -------------------------------- ### Register with a strategy Source: https://docs.bknd.io/usage/sdk Use the `register` method to create a new user account with a specified strategy, such as 'password'. ```javascript const { data } = await api.auth.register("password", { email: "...", password: "...", }); ``` -------------------------------- ### Serve Admin UI from Local Files Source: https://docs.bknd.io/integration/deno Configures bknd to serve the Admin UI static assets from a local `./public` directory using Hono's `serveStatic` middleware. ```typescript import { createRuntimeApp, serveStatic } from "bknd/adapter"; import { serveStatic } from "npm:hono/deno"; const app = await createRuntimeApp({ connection: { url: "file:data.db", }, serveStatic: serveStatic({ root: "./public", }), }); export default { fetch: app.fetch, }; ``` -------------------------------- ### Extend DB Interface for Type Completion Source: https://docs.bknd.io/usage/database Extend the `DB` interface with your schema to get type completion for entity-related functions. This is recommended for better development experience. ```typescript import { em } from "bknd"; import { Api } from "bknd/client"; const schema = em({ /* ... */ }); type Database = (typeof schema)["DB"]; declare module "bknd" { interface DB extends Database {} } const api = new Api({ /* ... */ }); const { data: posts } = await api.data.readMany("posts", {}); // `posts` is now typed as Database["posts"] ``` -------------------------------- ### Initialize API with Host and Request Object Source: https://docs.bknd.io/usage/sdk Initialize the API instance with a specified host and the current Request object, useful when the bknd instance is hosted elsewhere. ```typescript import { Api } from "bknd/client"; // replace this with the actual request let request: Request; const api = new Api({ host: "https://", request, }); ``` -------------------------------- ### Use authentication in SvelteKit server load function Source: https://docs.bknd.io/integration/sveltekit Pass request headers to `getApp` in `src/routes/+page.server.ts` to enable authentication. This example verifies authentication and retrieves user information. ```typescript 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(), }; }; ```