### Install better-auth-instantdb
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/00-START-HERE.md
Install the library using npm. This is the first step before setting up the server or client.
```bash
npm install better-auth-instantdb
```
--------------------------------
### Server-Side Configuration Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Example of setting up the InstantDB adapter for Better Auth on the server.
```typescript
// Server setup
import { instantAdapter } from "better-auth-instantdb"
const auth = betterAuth({
database: instantAdapter({
db: adminDb, // Required: InstantDB admin client
usePlural: true, // Optional: table naming convention
debugLogs: true // Optional: enable debug output
})
})
```
--------------------------------
### Server Setup with Better Auth and InstantDB Adapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Initialize the Better Auth adapter on your backend using InstantDB. This example shows how to configure email/password and social providers like GitHub.
```typescript
// server/auth.ts
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
// Initialize InstantDB admin client
const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID as string,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
// Create Better Auth instance with InstantDB adapter
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
}),
emailAndPassword: {
enabled: true
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string
}
},
plugins: [
// Add other plugins as needed
]
})
export const authClient = betterAuth()
```
--------------------------------
### Complete Application Structure Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Illustrates a full application structure integrating Better Auth and InstantDB. This includes frontend components, backend setup, authentication hooks, and routing.
```treeview
app/
├── layout.tsx # Root layout with Providers
├── page.tsx # Home page
├── providers.tsx # Client providers with auth setup
├── auth/
│ ├── signin/
│ │ └── page.tsx # Sign in form
│ ├── signup/
│ │ └── page.tsx # Sign up form
│ └── callback/
│ └── page.tsx # OAuth callback
├── dashboard/
│ └── page.tsx # Protected route
└── components/
├── user-menu.tsx # Sign out button
└── protected-route.tsx # Protected route wrapper
hooks/
└── use-auth.ts # Custom auth hook
server/
└── auth.ts # Backend auth setup
```
--------------------------------
### Install better-auth-instantdb
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Install the latest version of the better-auth-instantdb package using bun.
```bash
bun add better-auth-instantdb@latest
```
--------------------------------
### Basic InstantAuth Setup
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Demonstrates the basic setup of the InstantAuth component within a React application's provider structure. Ensure InstantDB and Better Auth clients are initialized before use.
```typescript
import { createAuthClient } from "better-auth/react"
import { init } from "@instantdb/react"
import { InstantAuth } from "better-auth-instantdb/react"
const authClient = createAuthClient()
const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID
})
export function Providers({ children }) {
return (
<>
{/* Synchronize auth state */}
{/* Other providers */}
{children}
>
)
}
```
--------------------------------
### Client-Side Configuration Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Example of configuring React hooks for Better Auth with InstantDB on the client.
```typescript
// Client setup
import { useInstantAuth } from "better-auth-instantdb/react"
useInstantAuth({
db: instantDbClient, // Required: InstantDB React client
authClient: authClient, // Required: Better Auth client
persistent: true // Optional: enable session caching
})
```
--------------------------------
### Client Provider Setup for Authentication Synchronization
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Wrap your application with the authentication provider to synchronize auth state between Better Auth and InstantDB. This example enables localStorage session caching.
```typescript
// app/providers.tsx
"use client"
import { createAuthClient } from "better-auth/react"
import { init } from "@instantdb/react"
import { useInstantAuth } from "better-auth-instantdb/react"
import schema from "@/instant.schema"
// Initialize clients
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_APP_URL
})
export const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID as string,
schema
})
// Provider component
export function Providers({ children }) {
// Sync auth state between Better Auth and InstantDB
useInstantAuth({
db,
authClient,
persistent: true // Enable localStorage session caching
})
return (
{children}
)
}
```
--------------------------------
### Minimal Server and Client Setup
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Set up the Better Auth server with the InstantDB adapter and configure the client for authentication. Ensure you have the necessary imports for both server and client components.
```typescript
// Server
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
export const auth = betterAuth({
database: instantAdapter({ db: adminDb })
})
// Client
import { useInstantAuth } from "better-auth-instantdb/react"
useInstantAuth({ db, authClient, persistent: true })
```
--------------------------------
### InstantAdapter Configuration Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/types.md
Demonstrates how to instantiate the InstantDB adapter with specific configuration options. Ensure you import the 'instantAdapter' function and have your 'adminDb' client ready.
```typescript
import { instantAdapter } from "better-auth-instantdb"
const adapter = instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
})
```
--------------------------------
### Basic Usage Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Demonstrates how to use the InstantAuth component at the root of your application to synchronize authentication state.
```APIDOC
## Basic Usage
### Description
Integrate the `InstantAuth` component into your application's provider setup to automatically synchronize authentication state.
### Example
```typescript
import { createAuthClient } from "better-auth/react"
import { init } from "@instantdb/react"
import { InstantAuth } from "better-auth-instantdb/react"
const authClient = createAuthClient()
const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID
})
export function Providers({ children }) {
return (
<>
{/* Synchronize auth state */}
{/* Other providers */}
{children}
>
)
}
```
```
--------------------------------
### Server Setup with InstantAdapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/00-START-HERE.md
Configure the server-side authentication using better-auth and the instantAdapter. Ensure you provide the InstantDB admin client to the adapter.
```typescript
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
export const auth = betterAuth({
database: instantAdapter({
db: adminDb, // Required: InstantDB admin client
usePlural: true, // Optional: table naming (default: true)
debugLogs: false // Optional: debug output (default: false)
})
})
```
--------------------------------
### App Root Setup (Next.js)
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Illustrates how to integrate the InstantAuth component at the root of a Next.js application for global authentication state synchronization. This setup ensures consistent auth state across the entire application.
```typescript
// app/layout.tsx
import { Providers } from "./providers"
export default function RootLayout({ children }) {
return (
{children}
)
}
// app/providers.tsx
import { InstantAuth } from "better-auth-instantdb/react"
import { authClient } from "@/lib/auth-client"
import { db } from "@/database/instant"
export function Providers({ children }) {
return (
<>
{/* Other providers... */}
{children}
>
)
}
```
--------------------------------
### Example Better Auth Schema and Link Generation
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-links.md
This example demonstrates how to define a Better Auth schema with a user and session model, including a foreign key reference. It then calls `createLinks` to generate the corresponding InstantDB link definitions.
```typescript
const schema = {
user: {
modelName: "user",
fields: {
id: { type: "string" },
email: { type: "string" }
}
},
session: {
modelName: "session",
fields: {
id: { type: "string" },
userId: {
type: "string",
references: {
model: "user",
onDelete: "cascade"
}
}
}
}
}
createLinks(schema, true)
```
--------------------------------
### Frontend Better Auth and InstantDB Provider Setup
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Sets up the React client for Better Auth and initializes InstantDB for client-side use. Requires VITE_INSTANT_APP_ID and a schema definition.
```typescript
// client/providers.tsx
import { createAuthClient } from "better-auth/react"
import { init } from "@instantdb/react"
import { useInstantAuth } from "better-auth-instantdb/react"
const authClient = createAuthClient()
const db = init({
appId: process.env.VITE_INSTANT_APP_ID as string,
schema
})
export function Providers({ children }) {
useInstantAuth({
db,
authClient,
persistent: true
})
return (
{children}
)
}
```
--------------------------------
### Initialize Better Auth with InstantDB Adapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-adapter.md
This example shows how to initialize Better Auth using the `instantAdapter`. It configures the InstantDB admin client and passes it to the adapter, along with options for pluralization and debug logging.
```typescript
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
}),
emailAndPassword: {
enabled: true
}
})
```
--------------------------------
### Example Debug Log Output
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/errors.md
This is an example of the detailed output you can expect when debug logs are enabled, showing entity operations, query details, and token management.
```text
Create Token user@example.com
Create sessions { id: "...", userId: "...", token: "..." }
Query { sessions: { $: { where: { userId: "..." } } } }
Result { sessions: [...] }
Update sessions { id: "..." } { token: "newtoken" }
```
--------------------------------
### useInstantAuth Hook Usage Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/types.md
Shows how to use the `useInstantAuth` hook with the necessary props. This example enables persistent session storage using localStorage.
```typescript
import { useInstantAuth } from "better-auth-instantdb/react"
useInstantAuth({
db: instantDbClient,
authClient: authClient,
persistent: true
})
```
--------------------------------
### Provider Wrapper Setup
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-auth.md
Illustrates setting up the useInstantAuth hook within a provider component for application-wide authentication state management. This is the recommended approach for integrating Better Auth and InstantDB.
```typescript
import { Providers } from "@/app/providers"
import { useInstantAuth } from "better-auth-instantdb/react"
export default function RootLayout({ children }) {
return (
{children}
)
}
// providers.tsx
import { authClient } from "@/lib/auth-client"
import { db } from "@/database/instant"
import { useInstantAuth } from "better-auth-instantdb/react"
export function Providers({ children }) {
useInstantAuth({ db, authClient, persistent: true })
return (
{children}
)
}
```
--------------------------------
### Basic Server-Side Setup with InstantDB Adapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Configure Better Auth with the InstantDB adapter. Ensure InstantDB admin client is initialized with your schema, app ID, and admin token. The adapter accepts optional `usePlural` and `debugLogs` options.
```typescript
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
// Create InstantDB admin client
export const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID as string,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
// Create Better Auth instance with InstantDB adapter
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true, // Optional: set to true if your schema uses plural table names
debugLogs: false // Optional: set to true to see detailed logs
}),
// Other Better Auth configuration options
emailAndPassword: {
enabled: true
},
})
```
--------------------------------
### Create InstantDB Adapter with Schema Generation
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-schema.md
Initialize the Better Auth adapter with InstantDB support, enabling schema generation. This setup is used when integrating Better Auth with an InstantDB backend.
```typescript
import { instantAdapter } from "better-auth-instantdb"
import { betterAuth } from "better-auth"
// Your schema
const schema = { /* Better Auth schema */ }
// Create adapter with schema generation support
export const auth = betterAuth({
database: instantAdapter({ db: adminDb, usePlural: true }),
})
```
--------------------------------
### Example InstantDB Schema Output
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-schema.md
This is an example of the TypeScript schema output generated by the createSchema function. It includes entity definitions with typed fields and link definitions for relationships.
```typescript
// Docs: https://www.instantdb.com/docs/modeling-data
import { i } from "@instantdb/react"
export const authSchema = i.schema({
entities: {
$users: i.entity({
id: i.string().unique(),
email: i.string().unique(),
name: i.string().optional(),
createdAt: i.date(),
updatedAt: i.date()
}),
sessions: i.entity({
id: i.string().unique(),
userId: i.string(),
token: i.string(),
expiresAt: i.date(),
createdAt: i.date()
})
},
links: {
sessionsUser: {
forward: {
on: "sessions",
has: "one",
label: "user"
},
reverse: {
on: "$users",
has: "many",
label: "sessions"
}
}
}
})
```
--------------------------------
### Persistent Sessions Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Shows how to enable offline session persistence by setting the `persistent` prop to `true`.
```APIDOC
## With Persistent Sessions
### Description
Enable offline session persistence by setting the `persistent` prop to `true`. This allows the session state to be available instantly on page reload and work offline.
### Example
```typescript
export function Providers({ children }) {
return (
<>
{/* Persist session to localStorage for offline access */}
{children}
>
)
}
```
### Benefits
- Session state available instantly on page reload (before server check).
- Works offline while the page is open.
- Gracefully degrades if localStorage is unavailable.
```
--------------------------------
### Client Setup with useInstantAuth Hook
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/00-START-HERE.md
Set up the client-side authentication synchronization using the useInstantAuth hook. This requires the InstantDB React client and the Better Auth client. Session caching can be enabled with the 'persistent' option.
```typescript
import { useInstantAuth } from "better-auth-instantdb/react"
useInstantAuth({
db: instantDbClient, // Required: InstantDB React client
authClient, // Required: Better Auth client
persistent: true // Optional: enable session caching
})
```
--------------------------------
### Define InstantDB Permissions
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Create an `instant.perms.ts` file to define granular permissions for your InstantDB schema entities. This example shows rules for users, accounts, sessions, verifications, and profiles, including binding rules based on ownership and authentication status.
```typescript
// instant.perms.ts
import type { InstantRules } from "@instantdb/react";
const rules = {
// Prevent creation of new attributes without explicit schema changes
attrs: {
allow: {
$default: "false",
},
},
// Auth entities permissions
users: {
bind: ["isOwner", "auth.id != null && auth.id == data.id"],
allow: {
view: "isOwner",
create: "false",
delete: "false",
update: "isOwner && (newData.email == data.email) && (newData.emailVerified == data.emailVerified) && (newData.createdAt == data.createdAt)",
},
},
accounts: {
bind: ["isOwner", "auth.id != null && auth.id == data.userId"],
allow: {
view: "isOwner",
create: "false",
delete: "false",
update: "false",
},
},
sessions: {
bind: ["isOwner", "auth.id != null && auth.id == data.userId"],
allow: {
view: "isOwner",
create: "false",
delete: "false",
update: "false",
},
},
verifications: {
allow: {
$default: "false"
}
},
// Optional permissions (public profile example)
profiles: {
bind: ["isOwner", "auth.id != null && auth.id == data.id"],
allow: {
view: "true",
create: "false",
delete: "false",
update: "isOwner",
},
},
// Add your custom entity permissions here
}
export default rules;
```
--------------------------------
### Example Query Built by fetchEntities
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/adapter-operations.md
Illustrates the structure of a query object constructed by the internal fetchEntities function, including filtering, pagination, and sorting parameters.
```typescript
const query = {
sessions: {
$: {
where: { userId: "user-123", verified: true },
limit: 10,
offset: 0,
order: { createdAt: "desc" }
}
}
}
```
--------------------------------
### Component-Level Setup
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-auth.md
Shows how to use the useInstantAuth hook directly within a specific component for localized authentication state synchronization. This provides more granular control over where the synchronization logic is applied.
```typescript
import { useInstantAuth } from "better-auth-instantdb/react"
export function AuthManager() {
useInstantAuth({ db, authClient })
return <>{/* other components */}>
}
```
--------------------------------
### Environment Variables for InstantDB and OAuth
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Configure essential environment variables in your `.env.local` file for InstantDB integration and OAuth providers like GitHub. These variables are crucial for application setup and authentication.
```bash
# .env.local
VITE_INSTANT_APP_ID=your_instantdb_app_id
INSTANT_ADMIN_TOKEN=your_instantdb_admin_token
NEXT_PUBLIC_INSTANT_APP_ID=your_instantdb_app_id
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
```
--------------------------------
### Core Documentation Directory Structure
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/00-START-HERE.md
This snippet outlines the directory structure for the core documentation files, including the main reference guide, overview, types, configuration, and error handling.
```tree
├── README.md # Main reference guide
├── index.md # Overview & quick links
├── types.md # Type definitions
├── configuration.md # Setup reference
├── errors.md # Error handling
├── usage-examples.md # Working code examples
└── MANIFEST.md # This documentation's structure
```
--------------------------------
### Hook vs. Component Usage Comparison
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-auth.md
Compares the direct usage of the useInstantAuth hook for more control versus using the simpler InstantAuth component wrapper. Choose the hook for complex scenarios and the component for straightforward provider-level setup.
```typescript
// With hook (more control)
useInstantAuth({ db, authClient, persistent: true })
// With component (simpler)
```
--------------------------------
### Initialize InstantAdapter with Basic Configuration
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Configure the InstantAdapter with a database client, and optionally enable plural table names and debug logs.
```typescript
instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: false
})
```
--------------------------------
### useHydrated Hook Example
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/utilities.md
Demonstrates how to use the `useHydrated` hook to conditionally render components only after client-side hydration. Import from `better-auth-instantdb/react`.
```typescript
import { useHydrated } from "better-auth-instantdb/react"
export function ClientOnlyComponent() {
const hydrated = useHydrated()
if (!hydrated) {
// Skip rendering until hydrated
return null
}
// This renders only after client-side hydration
return Client-side content
}
```
--------------------------------
### Backend InstantDB Initialization
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Initialize InstantDB for backend use with admin privileges. INSTANT_ADMIN_TOKEN must be set.
```typescript
// These stay on the server
const adminDb = init({
adminToken: process.env.INSTANT_ADMIN_TOKEN // Private
})
```
--------------------------------
### Error Log Example for Unfound Models
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-links.md
Illustrates the warning message logged when a referenced model cannot be found in the schema, leading to the link being skipped.
```typescript
Warning: Could not find entity name for model "undefined" referenced by session.userId
```
--------------------------------
### Main Entry Point Exports
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/MANIFEST.md
These are the core functions exported from the main 'better-auth-instantdb' package, providing database adapter factory, authentication synchronization, and query utilities.
```APIDOC
## Main Entry Point (`better-auth-instantdb`)
### Description
Provides core functionalities for database interaction and authentication synchronization.
### Functions
- **`instantAdapter()`**
- **Description**: Database adapter factory.
- **Signature**: `instantAdapter(config: InstantAdapterConfig): InstantAdapter`
- **`instantAuth()`**
- **Description**: Auth synchronization function.
- **Signature**: `instantAuth(client: AuthClient): void`
- **`parseWhere()`**
- **Description**: Query conversion utility.
- **Signature**: `parseWhere(where: Where): ParsedWhere`
```
--------------------------------
### Initialize InstantDB Admin Client and BetterAuth
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Initialize the InstantDB admin client with schema, app ID, and admin token, then integrate it with BetterAuth using the instantAdapter.
```typescript
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID as string,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
export const auth = betterAuth({
database: instantAdapter({ db: adminDb }),
// ... other config
})
```
--------------------------------
### Full Backend Better Auth Configuration with InstantDB
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Complete server-side configuration for Better Auth using the InstantDB adapter. Requires InstantDB credentials and social provider client IDs/secrets.
```typescript
// server/auth.ts
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID as string,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
}),
emailAndPassword: {
enabled: true
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string
}
}
})
```
--------------------------------
### Count Entities Matching Criteria
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/adapter-operations.md
Counts entities in a specified model that match given query conditions. Use this to get the number of records satisfying specific filters.
```typescript
const count = await adapter.count({
model: "session",
where: [
{ field: "userId", value: "user-123", operator: "eq" },
{ field: "verified", value: true, operator: "eq" }
]
})
```
--------------------------------
### Module Structure Overview
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/00-START-HERE.md
This diagram illustrates the main entry points and modules within the better-auth-instantdb project, including the database adapter and authentication functions, as well as React-specific hooks and components.
```tree
better-auth-instantdb
├── Main entry ("better-auth-instantdb")
│ ├── instantAdapter() - Database adapter factory
│ └── instantAuth() - Auth sync function
│
└── React entry ("better-auth-instantdb/react")
├── InstantAuth - Component
├── useInstantAuth() - Setup hook
├── useInstantSession() - Session hook
└── usePersistentSession() - Persistence hook
```
--------------------------------
### Configure InstantAdapter for Plural and Singular Table Names
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Demonstrates how to configure the instantAdapter to match InstantDB schema naming conventions, using either plural or singular table names.
```typescript
// Schema has plural names: users, sessions, accounts
instantAdapter({
db: adminDb,
usePlural: true // Matches schema
})
// Schema has singular names: user, session, account
instantAdapter({
db: adminDb,
usePlural: false // Matches schema
})
```
--------------------------------
### Accessing Session Data with useInstantSession
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Use the `useInstantSession` hook to retrieve authenticated user data. This example shows how to handle loading, error, and unauthenticated states, and display user information.
```typescript
"use client"
import { useInstantSession } from "better-auth-instantdb/react"
import { authClient, db } from "@/app/providers"
export default function Dashboard() {
const { data, isPending, error } = useInstantSession({
authClient,
db,
persistent: true
})
if (isPending) {
return Loading...
}
if (error) {
return Error: {error.message}
}
if (!data) {
return
}
const { user } = data
return (
Welcome, {user?.name || user?.email}
Email: {user?.email}
Created: {user?.createdAt?.toLocaleDateString()}
)
}
```
--------------------------------
### Push Schema and Permissions to InstantDB
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Use the InstantDB CLI to push your generated schema and permissions files to your InstantDB application. Run these commands in your terminal.
```bash
# Push schema
npx instant-cli@latest push schema
# Push permissions
npx instant-cli@latest push perms
```
--------------------------------
### Frontend InstantDB Initialization
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Initialize InstantDB for frontend use, exposing the appId. Ensure VITE_INSTANT_APP_ID is set.
```typescript
// These are exposed to the browser
const db = init({
appId: process.env.VITE_INSTANT_APP_ID // Public
})
```
--------------------------------
### InstantAuth Component vs. useInstantAuth Hook
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Compares the declarative component approach with the imperative hook usage. The component is suitable for provider-level setup, while the hook offers more flexibility for coordinating with other effects.
```typescript
// Component (simpler)
// Hook (more flexible)
useInstantAuth({ db, authClient, persistent: true })
```
--------------------------------
### instantAdapter Function
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-adapter.md
Creates a Better Auth database adapter that utilizes InstantDB as the underlying database. This function takes a configuration object and returns a database adapter factory.
```APIDOC
## instantAdapter Function
### Description
Creates a Better Auth database adapter that uses InstantDB as the underlying database. This function handles all database operations between Better Auth and InstantDB, including CRUD, queries, and transactions.
### Signature
```typescript
function instantAdapter(config: InstantAdapterConfig): ReturnType
```
### Parameters
#### `config` (InstantAdapterConfig) - Required
Configuration object for the adapter.
- **`config.db`** (`InstantAdminDatabase`) - Required - An initialized InstantDB admin client instance.
- **`config.usePlural`** (`boolean`) - Optional - Defaults to `true`. Whether table names in your schema use plural forms (e.g., `users` vs `user`).
- **`config.debugLogs`** (`DBAdapterDebugLogOption`) - Optional - Defaults to `false`. Enable detailed debug logging for troubleshooting.
### Returns
A Better Auth database adapter factory function. This factory can be passed to the `database` option in `betterAuth()` configuration.
### Special Handling
- **User Entity Mapping**: Automatically maps Better Auth's `user` model to InstantDB's `$users` reserved entity name.
- **Session Token Generation**: Generates an InstantDB authentication token using `db.auth.createToken()` when creating a session and overrides the session token.
- **Session Teardown**: Calls `db.auth.signOut()` to invalidate sessions on the InstantDB side when deleting sessions.
- **Join Support**: Wraps `findOne` to automatically populate the `user` property when fetching sessions with `join: { user: true }`.
### Example
```typescript
import { betterAuth } from "better-auth"
import { instantAdapter } from "better-auth-instantdb"
import { init } from "@instantdb/admin"
import schema from "@/instant.schema"
const adminDb = init({
schema,
appId: process.env.VITE_INSTANT_APP_ID,
adminToken: process.env.INSTANT_ADMIN_TOKEN,
useDateObjects: true
})
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
}),
emailAndPassword: {
enabled: true
}
})
```
### Error Handling
The adapter throws errors for:
- Missing user on session creation.
- InstantDB query failures.
- Batch operation transaction failures.
These errors propagate up to Better Auth.
```
--------------------------------
### Using createSchema to Generate Full Schema
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-links.md
Demonstrates the typical usage of createSchema, which internally calls createLinks to generate the complete schema file.
```typescript
const fullSchema = createSchema(tables, usePlural)
// Internally calls createLinks(tables, usePlural)
```
--------------------------------
### Multiple InstantAuth Instances
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/instant-auth-component.md
Demonstrates rendering multiple InstantAuth components. While safe, it's recommended to use a single instance at the provider level for optimal performance.
```typescript
<>
{/* Both will sync correctly */}
>
```
--------------------------------
### InstantDB Environment Variables
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Required environment variables for InstantDB credentials and development mode.
```bash
# InstantDB credentials
VITE_INSTANT_APP_ID=your_app_id
INSTANT_ADMIN_TOKEN=your_admin_token
# For development
NODE_ENV=development
```
--------------------------------
### Basic and Persistent useInstantAuth Usage
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-auth.md
Demonstrates the basic and persistent usage of the useInstantAuth hook within a React component setup. Import necessary clients and the hook, then call useInstantAuth with the db and authClient, optionally setting persistent to true.
```typescript
import { createAuthClient } from "better-auth/react"
import { init } from "@instantdb/react"
import { useInstantAuth } from "better-auth-instantdb/react"
const authClient = createAuthClient()
const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID
})
export function Providers({ children }) {
// Basic usage
useInstantAuth({ db, authClient })
// Or with persistence
useInstantAuth({ db, authClient, persistent: true })
return children
}
// Can also be used directly in a component
export function MyComponent() {
useInstantAuth({ db, authClient, persistent: true })
return ...
}
```
--------------------------------
### Generate InstantDB Schema File
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Use the Better Auth CLI to generate the InstantDB schema file. This command should be run in your terminal.
```bash
npx @better-auth/cli generate
```
--------------------------------
### Main Package Exports
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Exports from the main 'better-auth-instantdb' package.
```typescript
export { instantAdapter } from "./adapter/instant-adapter"
export { instantAuth } from "./shared/instant-auth"
```
--------------------------------
### Basic useInstantSession Usage
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-session.md
Fetches session data, authenticates with InstantDB, queries user profile, and manages loading states. Ensure `db` and `authClient` are correctly initialized.
```typescript
import { useInstantSession } from "better-auth-instantdb/react"
import { authClient } from "@/lib/auth-client"
import { db } from "@/database/instant"
export function UserProfile() {
const { data, isPending, error } = useInstantSession({
db,
authClient
})
if (isPending) return Loading...
if (error) return Error: {error.message}
if (!data) return Not authenticated
const { user } = data
return (
{user.name}
{user.email}
Created: {user.createdAt}
{/* Other user fields from InstantDB are available here */}
)
}
```
--------------------------------
### Full Authentication Flow with useInstantSession
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-session.md
Demonstrates how to use the useInstantSession hook to fetch and display user data, handling loading and error states. This is useful for building authenticated user interfaces that require up-to-date information from InstantDB.
```typescript
import { useInstantSession } from "better-auth-instantdb/react"
export function Dashboard() {
const { data: session, isPending, error } = useInstantSession({
db,
authClient,
persistent: true
})
if (isPending) {
return
}
if (error) {
return {error.message}
}
if (!session) {
return
}
// User is authenticated and InstantDB data is loaded
const user = session.user
return (
)
}
```
--------------------------------
### Client-Side InstantDB Initialization and Auth Sync
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Initialize the InstantDB client for React and integrate `InstantAuth` to synchronize authentication state. Pass the initialized DB client and your auth client to the `InstantAuth` component. The `persistent` prop ensures state persistence.
```typescript
import authClient from "@/lib/auth-client"
import { init } from "@instantdb/react"
import { useInstantAuth } from "better-auth-instantdb"
// Initialize InstantDB client
const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID
})
export function Providers({ children }) {
return (
<>
{children}
>
)
}
```
--------------------------------
### Initialize with Date Object Handling
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Initialize InstantDB with useDateObjects set to true for proper handling of date and time values.
```typescript
const adminDb = init({
useDateObjects: true
})
```
--------------------------------
### Import Core Adapter and Auth Function
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Import the main adapter and authentication synchronization function from the core package.
```typescript
// Main adapter and auth function
import { instantAdapter, instantAuth } from "better-auth-instantdb"
```
--------------------------------
### Basic User Sign-Up Form
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Implements a client-side form for user sign-up using email and password. It utilizes the `authClient` to handle the sign-up process and provides feedback on loading and errors.
```typescript
// app/signup/page.tsx
"use client"
import { useState } from "react"
import { authClient } from "@/app/providers"
export default function SignUp() {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError(null)
try {
const response = await authClient.signUp.email({
email,
password,
name: email.split("@")[0]
})
if (response.error) {
setError(response.error.message)
} else {
// User created, session established
window.location.href = "/dashboard"
}
} catch (err) {
setError("Failed to sign up")
} finally {
setLoading(false)
}
}
return (
)
}
```
--------------------------------
### create
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/adapter-operations.md
Creates a new entity in the database. For sessions, it automatically generates an InstantDB token and handles transaction creation. For users, it maps the 'user' model to the '$users' entity.
```APIDOC
## create
### Description
Creates a new entity in the database. For sessions, it automatically generates an InstantDB token and handles transaction creation. For users, it maps the 'user' model to the '$users' entity.
### Method
`create`
### Parameters
#### Request Body
- **data** (Record) - Required - Entity data including required fields (id, email, etc.)
- **model** (string) - Required - Model name (user, session, account, etc.)
### Response
#### Success Response (200)
- **data** (Record) - The created entity with all fields
### Request Example
```typescript
// Create a user
const user = await adapter.create({
model: "user",
data: {
id: "user-123",
email: "user@example.com",
name: "John Doe",
createdAt: new Date(),
updatedAt: new Date()
}
})
// Create a session (automatically generates token)
const session = await adapter.create({
model: "session",
data: {
id: "session-456",
userId: "user-123",
expiresAt: futureDate,
createdAt: new Date(),
updatedAt: new Date()
}
})
// Result includes: token (generated by InstantDB), refreshToken, etc.
```
### Error Conditions
- User not found when creating session (references invalid user)
- InstantDB token generation failure
- Transaction failure (entity or links)
```
--------------------------------
### Root Layout with Providers
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Sets up the root layout for the application, including the necessary authentication providers. This component should wrap the main application content to enable authentication features.
```typescript
// app/layout.tsx
import { Providers } from "./providers"
export default function RootLayout({ children }) {
return (
{children}
)
}
```
--------------------------------
### Build Project from Source
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Compile the project using npm scripts. Use 'npm run build' for a standard TypeScript compilation or 'npm run dev' to enable watch mode for continuous development.
```bash
# TypeScript compilation
npm run build
# Watch mode
npm run dev
```
--------------------------------
### Enable Debug Logs for InstantDB Adapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/usage-examples.md
Enable debug logs for the InstantDB adapter in development environments by setting the `debugLogs` option to `process.env.NODE_ENV === "development"`. This helps in monitoring adapter operations.
```typescript
// server/auth.ts
export const auth = betterAuth({
database: instantAdapter({
db: adminDb,
usePlural: true,
debugLogs: process.env.NODE_ENV === "development"
})
})
// Logs will show all adapter operations
```
--------------------------------
### Enable Development Logging
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/errors.md
Enable debug logs for the instantAdapter during development environments. This helps in troubleshooting by providing detailed logs.
```typescript
// Enable during development
instantAdapter({
db: adminDb,
debugLogs: process.env.NODE_ENV === "development"
})
```
--------------------------------
### Initialize Client-Side InstantDB with Schema
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/README.md
Update your client-side InstantDB initialization to include your custom schema. This ensures the InstantDB client is aware of your data structure.
```typescript
import { init } from "@instantdb/react"
import schema from "../../instant.schema"
export const db = init({
appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID,
schema
})
```
--------------------------------
### Configure InstantDB Adapter with Pluralization Setting
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/errors.md
Ensure the `usePlural` configuration option in the InstantDB adapter matches your schema's naming conventions (singular vs. plural entity names). Incorrect settings can lead to 'Could not find entity name' errors.
```typescript
// Check your schema
const schema = {
users: { /* ... */ }, // Plural
sessions: { /* ... */ } // Plural
}
// Match configuration
instantAdapter({
db: adminDb,
usePlural: true // Matches schema
})
```
--------------------------------
### Complete Session Flow with useInstantSession
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-persistent-session.md
Demonstrates the complete flow of using the useInstantSession hook with persistence enabled. It handles loading, error, and session states to display the appropriate UI.
```typescript
import { useInstantSession } from "better-auth-instantdb/react"
export function App() {
// Both useInstantSession and usePersistentSession work
const { data: session, isPending, error } = useInstantSession({
db,
authClient,
persistent: true
})
// First visit: isPending=false, data=null (no cached session)
// Return: Returns a loading skeleton briefly
// Subsequent visits: isPending=false, data={session} (from localStorage)
// Instant display of cached session while verifying with server
if (isPending) return
if (error) return
if (!session) return
return
}
```
--------------------------------
### Import Core Types
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/types.md
Import core types like InstantAdapterConfig, InstantAuthProps, SessionResult, and AuthClient from the 'better-auth-instantdb/react' or 'better-auth-instantdb' packages.
```typescript
import type { InstantAdapterConfig } from "better-auth-instantdb"
import type {
InstantAuthProps,
SessionResult,
AuthClient
} from "better-auth-instantdb/react"
```
--------------------------------
### Configure InstantAuth Component
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Use the `InstantAuth` component to achieve the same configuration as the `useInstantAuth` hook. Pass the `db`, `authClient`, and `persistent` props.
```typescript
```
--------------------------------
### Import React Hooks and Component
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/README.md
Import React-specific hooks and the InstantAuth component for frontend integration.
```typescript
// React hooks and component
import {
InstantAuth,
useInstantAuth,
useInstantSession,
usePersistentSession
} from "better-auth-instantdb/react"
```
--------------------------------
### Direct Usage of createLinks Function
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/create-links.md
Shows how to directly import and use the createLinks function, including manual formatting of the resulting link definitions for the schema.
```typescript
import { createLinks } from "better-auth-instantdb"
const links = createLinks(betterAuthSchema, true)
// Manually format for schema:
const linkDefinitions = Object.entries(links)
.map(([name, link]) => ({...}))
```
--------------------------------
### useInstantSession with Persistent Sessions
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/api-reference/use-instant-session.md
Illustrates how to enable persistent sessions using the `persistent: true` option, which utilizes localStorage for immediate data restoration and background validation.
```APIDOC
## useInstantSession with Persistence
### Description
Enables persistent session management by leveraging localStorage. On the initial load, the session is restored immediately if available in localStorage, and then validated against the server in the background.
### Usage
```typescript
export function UserProfile() {
const { data, isPending } = useInstantSession({
db,
authClient,
persistent: true // Enable localStorage persistence
})
// On first page load:
// 1. Restored from localStorage immediately (if available)
// 2. Validates against server in background
// 3. Updates if needed
}
```
### Parameters
- **db** (object) - Required - The InstantDB client instance.
- **authClient** (object) - Required - The Better Auth client instance.
- **persistent** (boolean) - Required - Set to `true` to enable localStorage persistence.
```
--------------------------------
### Enable Debug Logs for Better Auth Integration
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/errors.md
Enable debug logs by setting the `debugLogs` option to `true` or `"verbose"` when initializing the instantAdapter. This will provide detailed logs for troubleshooting integration issues.
```typescript
instantAdapter({
db: adminDb,
debugLogs: true // Or "verbose"
})
```
--------------------------------
### Enable Debug Logging in InstantAdapter
Source: https://github.com/daveycodez/better-auth-instantdb/blob/main/_autodocs/configuration.md
Configure the instantAdapter to enable debug logging, either basic or verbose, for troubleshooting adapter operations.
```typescript
// Development with debug logs
instantAdapter({
db: adminDb,
debugLogs: process.env.NODE_ENV === "development"
})
// Verbose logging for troubleshooting
instantAdapter({
db: adminDb,
debugLogs: "verbose"
})
```