bknd-client-setup
Use when setting up Bknd SDK in a frontend application. Covers Api class initialization, token storage, auth state handling, React integration with BkndBrowserApp and useApp hook, framework-specific setup (Vite, Next.js, standalone), and TypeScript type registration.
What this skill does
# Client Setup
Set up the Bknd TypeScript SDK in your frontend application.
## Prerequisites
- Bknd backend running (local or deployed)
- Frontend project initialized (React, Vue, vanilla JS, etc.)
- `bknd` package installed: `npm install bknd`
## When to Use UI Mode
Not applicable - client setup is code-only.
## When to Use Code Mode
- Always - SDK setup requires code configuration
- Choose approach based on architecture:
- **Standalone API client** - Connecting to separate Bknd backend
- **Embedded (BkndBrowserApp)** - Bknd runs in browser (Vite/React)
- **Framework adapter** - Next.js, Astro, etc.
## Approach 1: Standalone API Client
Use when connecting to a separate Bknd backend server.
### Step 1: Basic Setup
```typescript
import { Api } from "bknd";
const api = new Api({
host: "https://api.example.com", // Your Bknd backend URL
});
// Make requests
const { ok, data } = await api.data.readMany("posts");
```
### Step 2: Add Token Persistence
Store auth tokens across page refreshes:
```typescript
import { Api } from "bknd";
const api = new Api({
host: "https://api.example.com",
storage: localStorage, // Persists token as "auth" key
});
```
Custom storage key:
```typescript
const api = new Api({
host: "https://api.example.com",
storage: localStorage,
key: "myapp_auth", // Custom key instead of "auth"
});
```
### Step 3: Handle Auth State Changes
React to login/logout events:
```typescript
const api = new Api({
host: "https://api.example.com",
storage: localStorage,
onAuthStateChange: (state) => {
console.log("Auth state:", state);
// state.user - current user or undefined
// state.token - JWT or undefined
// state.verified - whether token was verified with server
},
});
```
### Step 4: Cookie-Based Auth (SSR)
For server-side rendering with cookies:
```typescript
const api = new Api({
host: "https://api.example.com",
credentials: "include", // Send cookies cross-origin
});
```
### Step 5: Full Configuration
```typescript
import { Api } from "bknd";
const api = new Api({
// Required
host: "https://api.example.com",
// Auth persistence
storage: localStorage,
key: "auth",
// Auth events
onAuthStateChange: (state) => {
if (state.user) {
console.log("Logged in:", state.user.email);
} else {
console.log("Logged out");
}
},
// Request options
credentials: "include", // For cookies
verbose: true, // Log requests (dev only)
// Data API defaults
data: {
defaultQuery: { limit: 20 },
},
});
export { api };
```
## Approach 2: React with BkndBrowserApp (Embedded)
Use when Bknd runs entirely in the browser (Vite + React).
### Step 1: Define Schema
```typescript
// bknd.config.ts
import { boolean, em, entity, text } from "bknd";
export const schema = em({
todos: entity("todos", {
title: text(),
done: boolean(),
}),
});
// Type registration for autocomplete
type Database = (typeof schema)["DB"];
declare module "bknd" {
interface DB extends Database {}
}
```
### Step 2: Configure BkndBrowserApp
```tsx
// App.tsx
import { BkndBrowserApp, type BrowserBkndConfig } from "bknd/adapter/browser";
import { schema } from "./bknd.config";
const config = {
config: {
data: schema.toJSON(),
auth: {
enabled: true,
jwt: {
secret: "your-secret-key", // Use env var in production
},
},
},
options: {
seed: async (ctx) => {
// Initial data (runs once on empty DB)
await ctx.em.mutator("todos").insertMany([
{ title: "Learn bknd", done: false },
]);
},
},
} satisfies BrowserBkndConfig;
export default function App() {
return (
<BkndBrowserApp {...config}>
<YourRoutes />
</BkndBrowserApp>
);
}
```
### Step 3: Use the useApp Hook
```tsx
import { useApp } from "bknd/adapter/browser";
function TodoList() {
const { api, app, user, isLoading } = useApp();
if (isLoading) return <div>Loading...</div>;
// api - Api instance for data/auth/media
// app - Full App instance
// user - Current user or null
// isLoading - True while initializing
const [todos, setTodos] = useState([]);
useEffect(() => {
api.data.readMany("todos").then(({ data }) => setTodos(data));
}, [api]);
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}
```
## Approach 3: React Standalone (External Backend)
Use when React connects to a separate Bknd server.
### Step 1: Create API Instance
```typescript
// lib/api.ts
import { Api } from "bknd";
export const api = new Api({
host: import.meta.env.VITE_BKND_URL || "http://localhost:7654",
storage: localStorage,
});
```
### Step 2: Create React Context
```tsx
// context/BkndContext.tsx
import { createContext, useContext, useEffect, useState, ReactNode } from "react";
import { Api, type TApiUser } from "bknd";
import { api } from "../lib/api";
type BkndContextType = {
api: Api;
user: TApiUser | null;
isLoading: boolean;
};
const BkndContext = createContext<BkndContextType | null>(null);
export function BkndProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<TApiUser | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Listen for auth changes
api.options.onAuthStateChange = (state) => {
setUser(state.user ?? null);
};
// Verify existing token on mount
api.verifyAuth().finally(() => {
setUser(api.getUser());
setIsLoading(false);
});
return () => {
api.options.onAuthStateChange = undefined;
};
}, []);
return (
<BkndContext.Provider value={{ api, user, isLoading }}>
{children}
</BkndContext.Provider>
);
}
export function useBknd() {
const ctx = useContext(BkndContext);
if (!ctx) throw new Error("useBknd must be used within BkndProvider");
return ctx;
}
```
### Step 3: Wrap App
```tsx
// main.tsx
import { BkndProvider } from "./context/BkndContext";
ReactDOM.createRoot(document.getElementById("root")!).render(
<BkndProvider>
<App />
</BkndProvider>
);
```
### Step 4: Use in Components
```tsx
function Profile() {
const { api, user, isLoading } = useBknd();
if (isLoading) return <div>Loading...</div>;
if (!user) return <div>Not logged in</div>;
return <div>Hello, {user.email}</div>;
}
```
## Approach 4: Next.js Integration
### Step 1: Create API Utility
```typescript
// lib/bknd.ts
import { Api } from "bknd";
// Client-side singleton
let clientApi: Api | null = null;
export function getClientApi() {
if (typeof window === "undefined") {
throw new Error("getClientApi can only be used client-side");
}
if (!clientApi) {
clientApi = new Api({
host: process.env.NEXT_PUBLIC_BKND_URL!,
storage: localStorage,
});
}
return clientApi;
}
// Server-side (per-request)
export function getServerApi(request?: Request) {
return new Api({
host: process.env.BKND_URL!,
request, // Extracts token from cookies/headers
});
}
```
### Step 2: Client Component
```tsx
"use client";
import { useEffect, useState } from "react";
import { getClientApi } from "@/lib/bknd";
export function PostList() {
const [posts, setPosts] = useState([]);
const api = getClientApi();
useEffect(() => {
api.data.readMany("posts").then(({ data }) => setPosts(data));
}, []);
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}
```
### Step 3: Server Component
```tsx
// app/posts/page.tsx
import { getServerApi } from "@/lib/bknd";
export default async function PostsPage() {
const api = getServerApi();
const { data: posts } = await api.data.readMany("posts");
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}
```
## TypeScript Type Registration
Get autocomplete for entity names and fields:
```typescript
// types/bknd.d.ts
import { em, entity, text, number } from "bkndRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.