### Create and Setup Vite Project Source: https://www.instantdb.com/docs/start-vanilla Use this command to create a new Vite project with Vanilla TypeScript and install the InstantDB core library. ```shell npx create-vite@latest -t vanilla-ts instant-vanilla cd instant-vanilla npm i @instantdb/core npm run dev ``` -------------------------------- ### Install Platform SDK Source: https://www.instantdb.com/docs/platform-api Install the Platform SDK for backend server integration. ```bash npm install @instantdb/platform ``` -------------------------------- ### Install InstantDB Python SDK Source: https://www.instantdb.com/docs/start-python Install the InstantDB Python SDK using pip or uv. ```shell uv add instantdb # or pip install instantdb ``` -------------------------------- ### Create Next.js App and Install InstantDB Source: https://www.instantdb.com/docs/storage Initializes a new Next.js project with Tailwind CSS and installs the InstantDB React library. ```shell npx create-next-app instant-storage --tailwind --yes cd instant-storage npm i @instantdb/react ``` -------------------------------- ### Install Instant CLI Source: https://www.instantdb.com/docs/platform-api Install the Instant CLI to manage apps from your terminal. ```bash npx instant-cli ``` -------------------------------- ### Install Docker on Ubuntu (Part 3) Source: https://www.instantdb.com/docs/self-hosting Install the Docker CE, CLI, and Compose plugins. ```shell sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ``` -------------------------------- ### Sign in with Instant Token Example Source: https://www.instantdb.com/docs/platform-api Example format of a token obtained after a user signs in with Instant, used for creating apps associated with the user's account. ```bash prt_xxx11x1xxx1xx1x11x1x1111xxx1xx11x11xxxx1x1x1x1111xxx11111xxx111x ``` -------------------------------- ### Scaffold a New TanStack Start Project with InstantDB Source: https://www.instantdb.com/docs/start-tanstack Use this command for the fastest way to start a new project with InstantDB pre-configured. ```shell npx create-instant-app -b tanstack-start ``` -------------------------------- ### Install Docker on Ubuntu (Part 1) Source: https://www.instantdb.com/docs/self-hosting Initial steps to set up the Docker repository on an Ubuntu system. ```shell apt update sudo apt install ca-certificates curl sudo install -m 0755 -d /etc/apt/keyrings sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc sudo chmod a+r /etc/apt/keyrings/docker.asc ``` -------------------------------- ### Start InstantDB with Caddy Source: https://www.instantdb.com/docs/self-hosting Build and start the InstantDB services using Docker Compose, including the Caddy reverse proxy. ```shell docker compose -f docker-compose.with-caddy.yml --env-file .env up --build ``` -------------------------------- ### Install Docker on Ubuntu (Part 2) Source: https://www.instantdb.com/docs/self-hosting Configure the Docker repository source list for apt. ```shell sudo tee /etc/apt/sources.list.d/docker.sources < { const unsubscribe = onAuthStateChanged(firebaseAuth, (user) => { if (user) { user.getIdToken().then((idToken) => { db.auth.signInWithIdToken({ idToken, clientName: FIREBASE_CLIENT_NAME, }); }); } else { db.auth.signOut(); } }); return () => unsubscribe(); }, []); const handleSignIn = async (e) => { e.preventDefault(); try { await signInWithEmailAndPassword(firebaseAuth, email, password); } catch (error) { console.error('Sign in error:', error); } }; const handleSignUp = async (e) => { e.preventDefault(); try { await createUserWithEmailAndPassword(firebaseAuth, email, password); } catch (error) { console.error('Sign up error:', error); } }; return ( <>
setEmail(e.target.value)} /> setPassword(e.target.value)} />
); } function SignedInComponent() { const user = db.useUser(); const handleSignOut = async () => { await firebaseAuth.signOut(); }; return (
Signed in as {user.email}!
); } export default App; ``` -------------------------------- ### Create a Blank TanStack Start App Manually Source: https://www.instantdb.com/docs/start-tanstack Initiate a new TanStack Start project without any pre-installed libraries. ```shell npx @tanstack/cli create my-app ``` -------------------------------- ### Full Clerk Integration Example with InstantDB (Next.js) Source: https://www.instantdb.com/docs/auth/clerk This example demonstrates how to use Clerk's Next.js library with InstantDB. It includes signing in to Instant using Clerk's JWT and handling user sessions. Ensure `CLERK_CLIENT_NAME` is replaced with your actual client name. ```javascript 'use client'; import { useAuth, ClerkProvider, SignInButton, SignedIn, SignedOut, } from '@clerk/nextjs'; import { init } from '@instantdb/react'; import { useEffect } from 'react'; // Instant app const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); // Use the clerk client name you set in the Instant dashboard auth tab const CLERK_CLIENT_NAME = 'REPLACE_ME'; function ClerkSignedInComponent() { const { getToken, signOut } = useAuth(); const signInToInstantWithClerkToken = async () => { // getToken gets the jwt from Clerk for your signed in user. const idToken = await getToken(); if (!idToken) { // No jwt, can't sign in to instant return; } // Create a long-lived session with Instant for your clerk user // It will look up the user by email or create a new user with // the email address in the session token. db.auth.signInWithIdToken({ clientName: CLERK_CLIENT_NAME, idToken: idToken, }); }; useEffect(() => { signInToInstantWithClerkToken(); }, []); const { isLoading, user, error } = db.useAuth(); if (isLoading) { return
Loading...
; } if (error) { return
Error signing in to Instant! {error.message}
; } if (user) { return (

Signed in with Instant through Clerk!

); } return (
); } function App() { return ( ); } export default App; ``` -------------------------------- ### Initialize InstantDB and Get Room Reference Source: https://www.instantdb.com/docs/presence-and-topics Initialize the InstantDB client and obtain a room reference using `db.room(roomType, roomId)`. This setup is for sharing presence and topics within a specific room. You can also use `db.room()` without arguments for a default room. ```typescript import { init } from '@instantdb/react'; // Instant app const APP_ID = '__APP_ID__'; // db will export all the presence hooks you need! const db = init({ appId: APP_ID }); // Specifying a room type and room id gives you the power to // restrict sharing to a specific room. However you can also just use // `db.room()` to share presence and topics to an Instant generated default room const roomId = 'hacker-chat-room-id'; const room = db.room('chat', roomId); ``` -------------------------------- ### Example Environment Variables for Production Source: https://www.instantdb.com/docs/self-hosting Configure public URLs and domain names for production deployment, especially when using Caddy. ```shell # Public URLs. Change these when deploying behind a domain or proxy. INSTANT_BACKEND_URL=https://api.myinstant.com INSTANT_DASHBOARD_URL=https://dash.myinstant.com S3_PUBLIC_ENDPOINT=https://files.myinstant.com # Domains used by the Caddy file. For production, point DNS at this host # and update the public URLs above to use these domains with https://. DASHBOARD_DOMAIN=dash.myinstant.com BACKEND_DOMAIN=api.myinstant.com STORAGE_DOMAIN=files.myinstant.com ``` -------------------------------- ### Copy and Edit Environment File Source: https://www.instantdb.com/docs/self-hosting Copy the example environment file to `.env` and open it for editing. ```shell cd instant/self-hosting cp .env.example .env nano .env ``` -------------------------------- ### Full Auth Flow Example with Login/Dashboard Source: https://www.instantdb.com/docs/auth A complete example demonstrating how to conditionally render a `Dashboard` component for signed-in users and a `Login` component for signed-out users. ```tsx import db from '../lib/db'; export default function App() { return (
); } function Dashboard() { // This component will only render if the user is signed in // so it's safe to call useUser here! const user = db.useUser(); return
Signed in as: {user.email}
; } function Login() { // Implement a login flow here via magic codes, OAuth, Clerk, etc. } ``` -------------------------------- ### Personal Access Token Example Source: https://www.instantdb.com/docs/platform-api Example format of a Personal Access Token used for authentication when creating long-lived apps. ```bash per_xxx11x1xxx1xx1x11x1x1111xxx1xx11x11xxxx1x1x1x1111xxx11111xxx111x ``` -------------------------------- ### Run Development Server Source: https://www.instantdb.com/docs/storage Command to start the development server for the InstantDB application. Access the app at localhost:3000. ```shell npm run dev ``` -------------------------------- ### Install MMKV for Faster Storage Source: https://www.instantdb.com/docs/start-rn Installs the MMKV package for InstantDB and its peer dependencies. This is an optional step for improving local data persistence performance. ```shell npm i @instantdb/react-native-mmkv npx expo install react-native-mmkv react-native-nitro-modules ``` -------------------------------- ### Install InstantDB React Library Source: https://www.instantdb.com/docs Add the InstantDB React library to your project's dependencies. ```shell npm i @instantdb/react ``` -------------------------------- ### Install InstantDB Svelte Library Source: https://www.instantdb.com/docs/start-svelte Add the InstantDB Svelte library to your project using npm. ```shell npm i @instantdb/svelte ``` -------------------------------- ### Install InstantDB SolidJS Library Source: https://www.instantdb.com/docs/start-solidjs Add the official InstantDB SolidJS package to your project's dependencies. ```shell npm i @instantdb/solidjs ``` -------------------------------- ### Temporary App Creation Output Source: https://www.instantdb.com/docs/platform-api Example output from creating a temporary app using the Platform SDK, showing app details. ```bash app -> { app: { id: '....', adminToken: '...' title: 'my-new-app', createdAt: '...' orgId: null, }, ... } ``` -------------------------------- ### Full Magic Code Authentication Example (Vanilla JS) Source: https://www.instantdb.com/docs/auth/magic-codes/vanilla This is a complete example for implementing magic code authentication in a vanilla JavaScript application. It includes rendering login steps, sending verification codes, and signing in users. Ensure you have a `
` in your HTML. ```javascript import { init, type User } from '@instantdb/core'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); const app = document.getElementById('app')!; let sentEmail = ''; function renderApp(user: User | undefined) { if (user) { renderMain(user); } else { renderLogin(); } } function renderMain(user: User) { app.innerHTML = `

Hello ${user.email}!

`; document.getElementById('sign-out')!.addEventListener('click', () => { db.auth.signOut(); }); } function renderLogin() { if (!sentEmail) { renderEmailStep(); } else { renderCodeStep(); } } function renderEmailStep() { app.innerHTML = `

Let's log you in

Enter your email, and we'll send you a verification code. We'll create an account for you too if you don't already have one.

`; document.getElementById('email-form')!.addEventListener('submit', (e) => { e.preventDefault(); const email = (document.getElementById('email-input') as HTMLInputElement) .value; sentEmail = email; renderLogin(); db.auth.sendMagicCode({ email }).catch((err) => { alert('Uh oh: ' + err.body?.message); sentEmail = ''; renderLogin(); }); }); } function renderCodeStep() { app.innerHTML = `

Enter your code

We sent an email to ${sentEmail}. Check your email, and paste the code you see.

`; document.getElementById('code-form')!.addEventListener('submit', (e) => { e.preventDefault(); const codeInput = document.getElementById('code-input') as HTMLInputElement; const code = codeInput.value; db.auth.signInWithMagicCode({ email: sentEmail, code }).catch((err) => { alert('Uh oh: ' + err.body?.message); codeInput.value = ''; }); }); } db.subscribeAuth((auth) => { renderApp(auth.user); }); ``` -------------------------------- ### Create InstantDB Client in TanStack Start Source: https://www.instantdb.com/docs/start-tanstack Configure the InstantDB client in your `src/lib/db.ts` file, ensuring it uses your application ID and schema. ```typescript import { init } from '@instantdb/react'; import schema from '../instant.schema'; export const db = init({ appId: import.meta.env.VITE_INSTANT_APP_ID!, schema, useDateObjects: true, }); ``` -------------------------------- ### Add InstantDB Vue Library Source: https://www.instantdb.com/docs/start-vue Install the official InstantDB Vue library to your project. ```shell npm i @instantdb/vue ``` -------------------------------- ### Install InstantDB Agent Rules Source: https://www.instantdb.com/docs/migrate-from-supabase Add InstantDB agent rules to your project. The --yes flag bypasses confirmation prompts. ```bash npx skills add instantdb/skills --yes ``` -------------------------------- ### Clone and Run InstantDB Locally Source: https://www.instantdb.com/docs/self-hosting Clone the InstantDB repository and start the services using Docker Compose for local development. ```shell git clone https://github.com/instantdb/instant.git cd instant/self-hosting docker compose --env-file .env.example up ``` -------------------------------- ### Full Magic Code Authentication Example in React Source: https://www.instantdb.com/docs/auth/magic-codes/react This comprehensive example demonstrates the complete magic code authentication flow for a React application. It includes components for handling email input, sending the magic code, and verifying the code entered by the user. Ensure you replace '__APP_ID__' with your actual InstantDB App ID. ```jsx 'use client'; import React, { useState } from 'react'; import { init } from '@instantdb/react'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); function App() { return ( <>
); } function Main() { const user = db.useUser(); return (

Hello {user.email}!

); } function Login() { const [sentEmail, setSentEmail] = useState(''); return (
{!sentEmail ? ( ) : ( )}
); } function EmailStep({ onSendEmail }: { onSendEmail: (email: string) => void }) { const inputRef = React.useRef(null); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const inputEl = inputRef.current!; const email = inputEl.value; onSendEmail(email); db.auth.sendMagicCode({ email }).catch((err) => { alert('Uh oh :' + err.body?.message); onSendEmail(''); }); }; return (

Let's log you in

Enter your email, and we'll send you a verification code. We'll create an account for you too if you don't already have one.

); } function CodeStep({ sentEmail }: { sentEmail: string }) { const inputRef = React.useRef(null); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const inputEl = inputRef.current!; const code = inputEl.value; db.auth.signInWithMagicCode({ email: sentEmail, code }).catch((err) => { inputEl.value = ''; alert('Uh oh :' + err.body?.message); }); }; return (

Enter your code

We sent an email to {sentEmail}. Check your email, and paste the code you see.

); } export default App; ``` -------------------------------- ### Initialize InstantDB Project Source: https://www.instantdb.com/docs/start-tanstack Run this command to set up your InstantDB project, including schema, permissions, and environment variables. ```shell npx instant-cli init ``` -------------------------------- ### Express / Node.js Framework Webhook Handler Source: https://www.instantdb.com/docs/webhooks Example of setting up a webhook handler in an Express.js application. It uses `express.raw` to get the raw request body for signature verification and then processes the webhook payload. ```APIDOC ## POST /api/instant-webhook ### Description Handles incoming webhook events from InstantDB in an Express.js application. It reads the raw request body, validates the signature, and processes the event. ### Method POST ### Endpoint /api/instant-webhook ### Parameters #### Headers - **instant-signature** (string) - Required - The signature of the webhook request. #### Request Body - **req** (express.Request) - The incoming Express request object. ### Request Example ```ts import express from 'express'; import { init, Webhooks } from '@instantdb/admin'; import schema from './instant.schema'; const { typedHandlers, combineHandlers } = Webhooks.helpers(); const handlers = combineHandlers( typedHandlers('$default', (record) => console.log(record)), ); const app = express(); app.post( '/api/instant-webhook', express.raw({ type: '*/*' }), async (req, res) => { const db = init({ appId: process.env.INSTANT_APP_ID!, schema, }); const signature = req.header('instant-signature')!; const body = req.body.toString('utf8'); try { const webhookBody = await db.webhooks.validate(signature, body); const payload = await db.webhooks.fetchPayloads(webhookBody); await db.webhooks.processPayload(handlers, payload); res.status(200).send('ok'); } catch (e) { res.status(400).send(String(e)); } }, ); ``` ### Response #### Success Response (200) - **ok** - Indicates successful processing of the webhook. #### Error Response (400) - **error message** (string) - A message describing the error during processing. ``` -------------------------------- ### Initialize Instant CLI Source: https://www.instantdb.com/docs Run the Instant CLI to initialize your project, set up the schema and permissions, and configure your environment variables. ```shell npx instant-cli init ``` -------------------------------- ### Getting Auth State with useAuth in Svelte Source: https://www.instantdb.com/docs/start-svelte Use `db.useAuth()` to access the current authentication state, including loading, error, and user information. This example displays different UI based on the auth status. ```svelte {#if auth.isLoading}
Loading...
{:else if auth.error}
Error: {auth.error.message}
{:else if auth.user}

Hello, {auth.user.isGuest ? 'Guest' : auth.user.email}!

{:else}

Please log in.

{/if} ``` -------------------------------- ### LinkedIn Login Integration with Expo AuthSession and InstantDB Source: https://www.instantdb.com/docs/auth/linkedin-oauth/rn-web Full example of a React Native component using Expo's AuthSession and InstantDB to implement a LinkedIn login flow. Includes setup for SignedIn/SignedOut states and handling authentication responses. ```javascript import { View, Text, Button, StyleSheet } from 'react-native'; import { init } from '@instantdb/react-native'; import { makeRedirectUri, useAuthRequest, useAutoDiscovery, } from 'expo-auth-session'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); function App() { return ( <> ); } function UserInfo() { const user = db.useUser(); return Hello {user.email}!; } function Login() { const discovery = useAutoDiscovery(db.auth.issuerURI()); const [request, _response, promptAsync] = useAuthRequest( { // The unique name you gave the OAuth client when you // registered it on the Instant dashboard clientId: 'YOUR_INSTANT_AUTH_CLIENT_NAME', redirectUri: makeRedirectUri(), }, discovery, ); return ( ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default App; ``` -------------------------------- ### Initialize InstantDB Client Source: https://www.instantdb.com/docs/backend Initialize the InstantDB client with your application ID and the path to your first-party endpoint. This setup is necessary for client-side interactions with InstantDB. ```typescript import { init } from '@instantdb/react'; export const db = init({ appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID!, firstPartyPath: '/api/instant', // the endpoint that you registered the route handler at. schema, useDateObjects: true, }); ``` -------------------------------- ### Run the Dev Server Source: https://www.instantdb.com/docs/create-instant-app Navigate into the newly created project directory and run the development server to see your Instant app in action. ```shell cd instant-demo npm run dev ``` -------------------------------- ### Create a New Instant Project Source: https://www.instantdb.com/docs/workflow Run this command to create a new project with starter code and default rules for your LLM agent. ```bash npx create-instant-app ``` -------------------------------- ### Install @react-oauth/google Package Source: https://www.instantdb.com/docs/auth/google-oauth/web-google-button Install the necessary package for integrating Google Sign-In in a React application. ```bash npm install @react-oauth/google ``` -------------------------------- ### Install Expo AuthSession Dependencies Source: https://www.instantdb.com/docs/auth/linkedin-oauth/rn-web Install the necessary Expo AuthSession and crypto libraries using npm or yarn. ```bash npx expo install expo-auth-session expo-crypto ``` -------------------------------- ### Install Google Sign-In Package Source: https://www.instantdb.com/docs/auth/google-oauth/rn-native Install the necessary Google Sign-In package for React Native using Expo. ```bash npx expo install @react-native-google-signin/google-signin ``` -------------------------------- ### Add Google Web Client with Dev Credentials Source: https://www.instantdb.com/docs/auth/google-oauth/web-redirect Use the Instant CLI to quickly set up Google OAuth for local web development using pre-configured developer credentials. ```bash npx instant-cli@latest auth client add \ --type google --app-type web --name google-web --dev-credentials ``` -------------------------------- ### Full React Native App Example with Apple Sign-In Source: https://www.instantdb.com/docs/auth/apple/native A complete React Native application demonstrating InstantDB initialization, user authentication state management, and Apple Sign-In integration. ```javascript import React, { useState } from 'react'; import { Button, View, Text, StyleSheet } from 'react-native'; import { init, tx } from '@instantdb/react-native'; import * as AppleAuthentication from 'expo-apple-authentication'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); function App() { return ( <> ); } function UserInfo() { const user = db.useUser(); return ( Hello {user.email}! ); } ``` -------------------------------- ### Get Event Source: https://www.instantdb.com/docs/webhooks Fetches a specific webhook event by its Instant Sequence Number (ISN). ```APIDOC ## getEvent ### Description Fetches a specific webhook event by its Instant Sequence Number (ISN). ### Method `getEvent(hookId: string, isn: string)` ### Parameters #### Path Parameters - **hookId** (string) - Required - The ID of the webhook. - **isn** (string) - Required - The Instant Sequence Number of the event to fetch. ### Response #### Success Response (200) - **event** (object) - The webhook event details. ### Request Example ```ts const event = await db.webhooks.manager.getEvent(hook.id, isn); ``` ``` -------------------------------- ### Get Users Source: https://www.instantdb.com/docs/http-api.md Retrieves a list of users, optionally filtered by a refresh token. ```APIDOC ## GET /admin/users ### Description Retrieves a list of users. Can be filtered by a refresh token. ### Method GET ### Endpoint /admin/users ### Query Parameters - **refresh_token** (string) - Optional - The refresh token to filter users. ### Request Example ```shell curl -X GET "https://api.instantdb.com/admin/users?refresh_token=$REFRESH_TOKEN" \ -H "Authorization: Bearer $ADMIN_TOKEN" \ -H "App-Id: $APP_ID" ``` ```