### Manual project setup commands Source: https://www.instantdb.com/llms-full.txt Commands to initialize a standard Vite SolidJS project and install the necessary InstantDB library. ```shell npx create-vite@latest -t solid-ts ``` ```shell npm i @instantdb/solidjs ``` ```shell npx instant-cli init ``` -------------------------------- ### Initialize and Run Todo Project Source: https://www.instantdb.com/examples/todos Commands to clone the repository, install dependencies, authenticate with the CLI, push the schema, and start the development server. ```bash # Clone repo git clone https://github.com/instantdb/instant-examples # Navigate into the todos example cd instant-examples/todos # Install dependencies pnpm i ``` ```bash pnpx instant-cli login ``` ```bash pnpx instant-cli init ``` ```bash pnpx instant-cli push ``` ```bash pnpm run dev ``` -------------------------------- ### Implement Google Sign-in in React Source: https://www.instantdb.com/docs/auth/google-oauth Full example showing the initialization of the Instant DB client and the setup for the Google OAuth provider. ```javascript 'use client'; import React, { useState } from 'react'; import { init } from '@instantdb/react'; import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); // e.g. 89602129-cuf0j.apps.googleusercontent.com const GOOGLE_CLIENT_ID = 'REPLACE_ME'; // Use the google client name in the Instant dashboard auth tab ``` -------------------------------- ### Clone and Install Dependencies Source: https://www.instantdb.com/examples/todos Commands to clone the repository and install the necessary packages for the Todo example. ```bash # Clone repo git clone https://github.com/instantdb/instant-examples # Navigate into the todos example cd instant-examples/todos # Install dependencies pnpm i ``` -------------------------------- ### Install Docker on Ubuntu Source: https://www.instantdb.com/llms-full.txt Standard commands to prepare the system and install the Docker engine. ```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 ``` ```shell sudo tee /etc/apt/sources.list.d/docker.sources < ); } function UserInfo() { const user = db.useUser(); return ( ``` -------------------------------- ### Install Platform SDK Source: https://www.instantdb.com/llms-full.txt Command to install the @instantdb/platform package for backend server integration. ```bash npm install @instantdb/platform ``` -------------------------------- ### Prepare Environment Variables Source: https://www.instantdb.com/llms-full.txt Initialize the .env file from the example template. ```shell cd instant/self-hosting cp .env.example .env nano .env ``` -------------------------------- ### Example Environment Configuration Source: https://www.instantdb.com/llms-full.txt Sample configuration for production URLs and domain settings. ```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 ``` -------------------------------- ### Firebase Authentication Integration Example Source: https://www.instantdb.com/docs/auth/firebase A complete example demonstrating how to initialize both InstantDB and Firebase, and how to handle authentication state. ```javascript 'use client'; import { init } from '@instantdb/react'; import { initializeApp } from 'firebase/app'; import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, } from 'firebase/auth'; import { useEffect, useState } from 'react'; // Instant app const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); // Use the firebase client name you set in the Instant dashboard auth tab const FIREBASE_CLIENT_NAME = 'REPLACE_ME'; const firebaseConfig = { // Use the same Project ID you set in the Instant dashboard auth tab projectId: 'REPLACE_ME', apiKey: 'REPLACE_ME', }; const firebaseApp = initializeApp(firebaseConfig); const firebaseAuth = getAuth(firebaseApp); function App() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { const unsubscribe = ``` -------------------------------- ### Start the development server Source: https://www.instantdb.com/docs/create-instant-app Navigate to the project directory and launch the development server. ```bash cd instant-demo npm run dev ``` -------------------------------- ### Install InstantDB SDK Source: https://www.instantdb.com/docs/start-python Use uv or pip to install the InstantDB package in your Python environment. ```shell uv add instantdb # or pip install instantdb ``` -------------------------------- ### Run the development server Source: https://www.instantdb.com/docs/create-instant-app Navigate into the project directory and start the development server. ```shell cd instant-demo npm run dev ``` -------------------------------- ### Implement Guest Authentication Source: https://www.instantdb.com/docs/auth/guest-auth Use db.auth.signInAsGuest() to initialize a guest session. This example demonstrates a basic React setup with sign-in and sign-out functionality. ```javascript 'use client'; import React, { useState } from 'react'; import { init, User } from '@instantdb/react'; // Visit https://instantdb.com/dash to get your APP_ID :) const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); function App() { return ( <>
); } function Main() { const user = db.useUser(); return (

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

); } function Login() { return (
); } export default App; ``` -------------------------------- ### Run Development Server Source: https://www.instantdb.com/examples/todos Start the local development server for the application. ```bash pnpm run dev ``` -------------------------------- ### Basic synchronous usage Source: https://www.instantdb.com/docs/start-python Example of initializing the Instant client and performing basic read/write operations. ```python from instantdb import Instant, id db = Instant( # You can pass these explicitly, by default they fall back to # INSTANT_APP_ID and INSTANT_APP_ADMIN_TOKEN environment variables app_id="__APP_ID__", admin_token="__ADMIN_TOKEN__", ) # Write data goal_id = id() db.transact(db.tx.goals[goal_id].update({"title": "Get fit"})) # Read data result = db.query({"goals": {}}) for goal in result["goals"]: print(goal["title"]) ``` -------------------------------- ### Initialize InstantDB and Auth Routes Source: https://www.instantdb.com/docs/streams Setup the database client and the required API route handler for authentication. ```typescript // src/lib/db.ts import { init } from '@instantdb/react/nextjs'; import schema from '@/instant.schema'; export const db = init({ appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID!, schema, firstPartyPath: '/api/instant', }); ``` ```typescript // src/app/api/instant/route.ts import { createInstantRouteHandler } from '@instantdb/react/nextjs'; export const { POST } = createInstantRouteHandler({ appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID!, }); ``` ```typescript // src/lib/adminDb.ts import { init } from '@instantdb/admin'; import schema from '@/instant.schema'; export const db = init({ appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID!, adminToken: process.env.INSTANT_APP_ADMIN_TOKEN!, schema, }); ``` -------------------------------- ### Initialize Next.js Project Source: https://www.instantdb.com/docs/storage Commands to create a new Next.js project and install the InstantDB React SDK. ```bash npx create-next-app instant-storage --tailwind --yes cd instant-storage npm i @instantdb/react ``` -------------------------------- ### Firebase Authentication Integration Example Source: https://www.instantdb.com/docs/auth/firebase A complete React example demonstrating how to listen for Firebase auth state changes and sign in to InstantDB using the Firebase ID token. ```javascript 'use client'; import { init } from '@instantdb/react'; import { initializeApp } from 'firebase/app'; import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, } from 'firebase/auth'; import { useEffect, useState } from 'react'; // Visit https://instantdb.com/dash to get your APP_ID :) const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); // Use the firebase client name you set in the Instant dashboard auth tab const FIREBASE_CLIENT_NAME = 'REPLACE_ME'; const firebaseConfig = { // Use the same Project ID you set in the Instant dashboard auth tab projectId: 'REPLACE_ME', apiKey: 'REPLACE_ME', }; const firebaseApp = initializeApp(firebaseConfig); const firebaseAuth = getAuth(firebaseApp); function App() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { 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(); }, []); ``` -------------------------------- ### Initialize InstantDB App Source: https://www.instantdb.com/docs/patterns Basic setup for initializing the InstantDB client with an application ID. ```javascript // Visit https://instantdb.com/dash to get your APP_ID :) const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); async function createMessage() { await db.transact( db.tx.messages[id()].update({ text: 'Hello world!' }) ); } ``` -------------------------------- ### Initialize InstantDB in React Source: https://www.instantdb.com/docs/init Basic setup for the InstantDB client at the root of a React application. ```javascript import { init } from '@instantdb/react'; // Instant app const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); function App() { return
; } ``` -------------------------------- ### Install InstantDB React library Source: https://www.instantdb.com/llms-full.txt Adds the necessary InstantDB dependency to the project. ```shell npm i @instantdb/react ``` -------------------------------- ### Initialize Next.js project Source: https://www.instantdb.com/docs/storage Commands to create a new Next.js application and install the InstantDB React package. ```shell npx create-next-app instant-storage --tailwind --yes cd instant-storage npm i @instantdb/react ``` -------------------------------- ### Full authentication flow example Source: https://www.instantdb.com/docs/auth Demonstrates conditional rendering for a dashboard and login screen. ```javascript 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. } ``` -------------------------------- ### Start Production Server with Caddy Source: https://www.instantdb.com/llms-full.txt Launch the stack using the Caddy-enabled compose file. ```shell docker compose -f docker-compose.with-caddy.yml --env-file .env up --build ``` -------------------------------- ### Scaffold a TanStack Start application Source: https://www.instantdb.com/llms-full.txt Initializes a new project using the TanStack CLI. ```shell npx @tanstack/cli create my-app ``` -------------------------------- ### Parse App Initialization Output Source: https://www.instantdb.com/docs/cli Example of piping the init-without-files output to jq for script integration. ```bash output=$(npx instant-cli@latest init-without-files --title "Hello World" --temp) if echo "$output" | jq -e '.error' > /dev/null; then echo "Error: $(echo "$output" | jq -r '.error')" exit 1 fi appId=$(echo "$output" | jq -r '.appId') adminToken=$(echo "$output" | jq -r '.adminToken') ``` -------------------------------- ### Initialize a Project Source: https://www.instantdb.com/docs/cli Sets up a project by generating schema and permission files, with an option for temporary apps. ```bash npx instant-cli@latest init ``` ```bash npx instant-cli@latest init --temp ``` -------------------------------- ### Initialize an Instant Project Source: https://www.instantdb.com/docs/cli Sets up a new project in the current directory by generating schema and permission files. ```shell npx instant-cli@latest init ``` ```shell npx instant-cli@latest init --temp ``` -------------------------------- ### Initialize a new project Source: https://www.instantdb.com/docs/workflow Use this command to create a new InstantDB project with starter code. ```bash npx create-instant-app ``` -------------------------------- ### Install MMKV dependencies Source: https://www.instantdb.com/llms-full.txt Commands to install the MMKV package and its required peer dependencies. ```shell npm i @instantdb/react-native-mmkv # Install MMKV peer dependencies npx expo install react-native-mmkv react-native-nitro-modules ``` -------------------------------- ### Initialize Local InstantDB Environment Source: https://www.instantdb.com/llms-full.txt Clone the repository and start the services using the provided environment configuration. ```shell git clone https://github.com/instantdb/instant.git cd instant/self-hosting docker compose --env-file .env.example up ``` -------------------------------- ### Install Expo AuthSession Dependencies Source: https://www.instantdb.com/docs/auth/github-oauth Install the required packages for handling authentication in an Expo project. ```shell npx expo install expo-auth-session expo-crypto ``` -------------------------------- ### Initialize InstantDB App Source: https://www.instantdb.com/examples/todos Create a new InstantDB application configuration. ```bash pnpx instant-cli init ``` -------------------------------- ### Webhook Verifier Java Setup Source: https://www.instantdb.com/docs/webhooks Initial setup for a Java-based webhook verifier using BouncyCastle. ```java // deps: org.bouncycastle:bcprov-jdk18on, com.fasterxml.jackson.core:jackson-databind import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Base64; import java.util.HexFormat; import java.util.HashMap; import java.util.Map; import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; import org.bouncycastle.crypto.signers.Ed25519Signer; public class WebhookVerifier { static final String JWKS_URL = "https://api.instantdb.com/.well-known/webhooks/jwks.json"; static final long TOLERANCE_SECONDS = 300; static final ObjectMapper ``` -------------------------------- ### Install Google Sign-In Package Source: https://www.instantdb.com/docs/auth/google-oauth Install the required dependency for native Google authentication in an Expo project. ```bash npx expo install @react-native-google-signin/google-signin ``` -------------------------------- ### Install React Google OAuth Package Source: https://www.instantdb.com/docs/auth/google-oauth Install the required dependency for integrating Google Sign-In in React applications. ```shell npm install @react-oauth/google ``` -------------------------------- ### Install React OAuth Dependencies Source: https://www.instantdb.com/docs/auth/google-oauth Install the required package for integrating the Google Sign-in button in React applications. ```bash npm install @react-oauth/google ``` -------------------------------- ### Scaffold TanStack Start Project Source: https://www.instantdb.com/llms-full.txt Uses the create-instant-app CLI tool to initialize a new project with InstantDB pre-configured. ```shell npx create-instant-app -b tanstack-start ``` -------------------------------- ### Create GET handler for stream resumption Source: https://www.instantdb.com/llms-full.txt Implement the GET handler to resume an existing stream using the activeStreamId stored in the chat state. ```ts // app/api/chat/[id]/stream/route.ts import { readChat } from '@util/chat-store'; import { UI_MESSAGE_STREAM_HEADERS } from 'ai'; import { after } from 'next/server'; import { createResumableStreamContext } from '@instantdb/resumable-stream'; export async function GET( _: Request, { params }: { params: Promise<{ id: string }> }, ) { const { id } = await params; const chat = await readChat(id); if (chat.activeStreamId == null) { // no content response when there is no active stream return new Response(null, { status: 204 }); } const streamContext = createResumableStreamContext({ waitUntil: after, appId: process.env.INSTANT_APP_ID, adminToken: process.env.INSTANT_APP_ADMIN_TOKEN, }); return new Response( await streamContext.resumeExistingStream(chat.activeStreamId), { headers: UI_MESSAGE_STREAM_HEADERS }, ); } ``` -------------------------------- ### GET /admin/rooms/presence Source: https://www.instantdb.com/docs/http-api Query for the data currently in a room. ```APIDOC ## GET /admin/rooms/presence ### Description Query for the data currently in a room. Useful for checking if a user is online. ### Method GET ### Endpoint https://api.instantdb.com/admin/rooms/presence ### Parameters #### Query Parameters - **room-type** (string) - Required - The type of the room. - **room-id** (string) - Required - The unique identifier of the room. ``` -------------------------------- ### Scaffold a new InstantDB project Source: https://www.instantdb.com/llms-full.txt Use the create-instant-app CLI to initialize a project with either Next.js or Vite. ```bash npx create-instant-app --next ``` ```bash npx create-instant-app --vite-react ``` -------------------------------- ### Type Attributes Source: https://www.instantdb.com/docs/modeling-data Example of defining a string attribute for an entity. ```typescript // instant.schema.ts const _schema = i.schema({ entities: { // ... posts: i.entity({ title: i.string(), // ... }), }, }); ``` -------------------------------- ### Scaffold and initialize a Vue project Source: https://www.instantdb.com/llms-full.txt Commands for setting up a new Vue project with InstantDB and initializing the database client. ```shell npx create-instant-app --vue ``` ```shell npm create vue@latest my-app ``` ```shell npm i @instantdb/vue ``` ```shell npx instant-cli init ``` -------------------------------- ### FastAPI Webhook Integration Source: https://www.instantdb.com/docs/start-python Example of integrating InstantDB webhooks with FastAPI. ```python from fastapi import FastAPI, Request, HTTPException from instantdb import AsyncInstant, InstantError app = FastAPI() db = AsyncInstant() async def on_goal_create(record): print("new goal:", record["after"]) handlers = {"goals": {"create": on_goal_create}} @app.post("/webhooks/instant") async def webhook_in(request: Request): body = await request.body() sig = request.headers.get("Instant-Signature", "") try: ``` -------------------------------- ### Asynchronous usage Source: https://www.instantdb.com/docs/start-python Example of using AsyncInstant for non-blocking operations with asyncio. ```python import asyncio from instantdb import AsyncInstant, id db = AsyncInstant() async def main(): goal_id = id() await db.transact(db.tx.goals[goal_id].update({"title": "Get fit"})) result = await db.query({"goals": {}}) for goal in result["goals"]: print(goal["title"]) asyncio.run(main()) ``` -------------------------------- ### Initialize SvelteKit and InstantDB Source: https://www.instantdb.com/llms-full.txt Commands to scaffold a new SvelteKit project, install the InstantDB dependency, and initialize the project configuration. ```shell npx sv create my-app ``` ```shell npm i @instantdb/svelte ``` ```shell npx instant-cli init ``` -------------------------------- ### Scaffold a new project Source: https://www.instantdb.com/docs/start-python Commands to initialize a new InstantDB project with Python support. ```bash npx create-instant-app --python my-app cd my-app uv sync ``` -------------------------------- ### Get Room Presence Source: https://www.instantdb.com/docs/start-python Retrieve presence data for a specific room. ```python sessions = db.rooms.get_presence("chat", "room-123") # {peer_id: {"data": ..., "peer-id": ..., "user": ...}} ``` -------------------------------- ### GET /admin/users Source: https://www.instantdb.com/docs/http-api Fetch an app user by email, id, or refresh_token. ```APIDOC ## GET /admin/users ### Description Fetch an app user by email, id, or refresh_token. ### Method GET ### Endpoint https://api.instantdb.com/admin/users ### Parameters #### Query Parameters - **email** (string) - Optional - The email address of the user. - **id** (string) - Optional - The unique identifier of the user. - **refresh_token** (string) - Optional - The refresh token of the user. ``` -------------------------------- ### Initialize InstantDB CLI Source: https://www.instantdb.com/llms-full.txt Run the CLI init command to authenticate, create schema files, and update environment variables. ```shell npx instant-cli init ``` -------------------------------- ### init(config) Source: https://www.instantdb.com/docs/init Initializes the InstantDB client with the provided configuration object. ```APIDOC ## init(config) ### Description Initializes the InstantDB client. This function connects your application to the backend using your unique application ID and allows for various configuration overrides. ### Parameters - **appId** (string) - Required - Your InstantDB application ID. - **schema** (object) - Optional - Instant schema export for typesafety and auto-completion. - **websocketURI** (string) - Optional - Custom WebSocket endpoint. Defaults to 'wss://api.instantdb.com/runtime/session'. - **apiURI** (string) - Optional - Custom HTTP API endpoint for auth and storage. Defaults to 'https://api.instantdb.com'. - **devtool** (boolean|object) - Optional - Configures the Instant dev tool. Defaults to true on localhost. - **verbose** (boolean) - Optional - Enables detailed console logging for debugging. - **logger** (object) - Optional - Custom logger object with debug, info, and error methods. - **queryCacheLimit** (number) - Optional - Maximum number of query subscriptions to cache for offline mode. Defaults to 10. - **useDateObjects** (boolean) - Optional - If true, date columns return Javascript Date objects. Defaults to false. ``` -------------------------------- ### Start the development server Source: https://www.instantdb.com/llms-full.txt Command to launch the Expo development server. ```shell npm run start ``` -------------------------------- ### Scaffold a new InstantDB project Source: https://www.instantdb.com/docs/start-python Initialize a new project structure including configuration files and schema definitions using the Instant CLI. ```shell npx create-instant-app --python my-app cd my-app uv sync ``` -------------------------------- ### Define Namespace Permissions Source: https://www.instantdb.com/llms-full.txt Examples of setting explicit or default permissions for a namespace. ```json { "todos": { "allow": { "view": "true", "create": "true", "update": "true", "delete": "true" } } } ``` ```json { "todos": { "allow": { "view": "true" } } } ``` ```json {} ``` -------------------------------- ### Case-Insensitive Matching with $ilike Source: https://www.instantdb.com/docs/instaql Example of using $ilike for case-insensitive substring matching. ```javascript const query = { goals: { $: { where: { 'todos.title': { $ilike: '%stand%' }, }, }, }, }; const { isLoading, error, data } = db.useQuery(query); ``` ```javascript console.log(data) { "goals": ``` -------------------------------- ### init Source: https://www.instantdb.com/docs/backend Initializes the Admin SDK to authenticate against the InstantDB admin API. ```APIDOC ## init ### Description Initializes the InstantDB Admin SDK instance. This must be called before performing any queries or writes. ### Parameters - **appId** (string) - Required - The unique identifier for your InstantDB application. - **adminToken** (string) - Required - The administrative token used for authentication, typically retrieved from environment variables. ``` -------------------------------- ### Initialize and Use InstantDB Synchronously Source: https://www.instantdb.com/docs/start-python Demonstrates basic client initialization and data operations. The app_id and admin_token can be provided explicitly or via environment variables. ```python from instantdb import Instant, id db = Instant( # You can pass these explicitly, by default they fall back to # INSTANT_APP_ID and INSTANT_APP_ADMIN_TOKEN environment variables app_id="__APP_ID__", admin_token="__ADMIN_TOKEN__", ) # Write data goal_id = id() db.transact(db.tx.goals[goal_id].update({"title": "Get fit"})) # Read data result = db.query({"goals": {}}) for goal in result["goals"]: print(goal["title"]) ``` -------------------------------- ### Querying with $like Source: https://www.instantdb.com/docs/instaql Example of using $like to filter goals by a specific suffix. ```javascript // Find all goals that end with the word "promoted!" const query = { goals: { $: { where: { title: { $like: '%promoted!' }, }, }, }, }; const { isLoading, error, data } = db.useQuery(query); ``` ```javascript console.log(data) { "goals": [ { "id": workId, "title": "Get promoted!", } ] } ``` -------------------------------- ### Define Data Model Schema Source: https://www.instantdb.com/docs/permissions Example schema definition for a goals collection. ```json { "goals": { "id": UUID, "title": string } } ``` -------------------------------- ### GET /.well-known/webhooks/jwks.json Source: https://www.instantdb.com/docs/webhooks Retrieves the public keys used to verify the Instant-Signature header. ```APIDOC ## GET /.well-known/webhooks/jwks.json ### Description Retrieves the JWK Set containing the public keys required to verify the Ed25519 signature of incoming webhooks. ### Method GET ### Endpoint https://api.instantdb.com/.well-known/webhooks/jwks.json ### Response #### Success Response (200) - **keys** (array) - A list of JWK objects containing the signing keys. ``` -------------------------------- ### Initialize a new project with Vite Source: https://www.instantdb.com/llms-full.txt Commands to scaffold a new Vanilla TypeScript project and install the Instant core package. ```shell npx create-vite@latest -t vanilla-ts instant-vanilla cd instant-vanilla npm i @instantdb/core npm run dev ``` -------------------------------- ### Configure Database Client Source: https://www.instantdb.com/llms-full.txt Setup the InstantDB client instance in src/lib/db.ts using environment variables and the project schema. ```ts import { init } from '@instantdb/svelte'; import schema from '../instant.schema'; export const db = init({ appId: import.meta.env.VITE_INSTANT_APP_ID!, schema, useDateObjects: true, }); ``` -------------------------------- ### Initialize App via CLI Source: https://www.instantdb.com/llms-full.txt Command to initialize a new long-lived application using the Instant CLI. ```bash npx instant-cli init-without-files --title my-long-lived-app --token YOUR_TOKEN ``` -------------------------------- ### Initialize React Native project with InstantDB Source: https://www.instantdb.com/llms-full.txt Commands to create an Expo project and install the required InstantDB and peer dependency packages. ```shell # Create an app with expo npx create-expo-app instant-rn-demo cd instant-rn-demo # Install instant npm i @instantdb/react-native # Install peer dependencies npm i @react-native-async-storage/async-storage @react-native-community/netinfo react-native-get-random-values ``` -------------------------------- ### Platform SDK App Creation Output Source: https://www.instantdb.com/llms-full.txt Example console output showing the structure of a created app object. ```bash app -> { app: { id: '....', adminToken: '...' title: 'my-new-app', createdAt: '...' orgId: null, }, ... } ``` -------------------------------- ### Initialize and use the InstantDB Python SDK Source: https://www.instantdb.com/llms-full.txt Initialize the database client and perform basic read/write operations. ```python from instantdb import Instant, id db = Instant( # You can pass these explicitly, by default they fall back to # INSTANT_APP_ID and INSTANT_APP_ADMIN_TOKEN environment variables app_id="__APP_ID__", admin_token="__ADMIN_TOKEN__", ) # Write data goal_id = id() db.transact(db.tx.goals[goal_id].update({"title": "Get fit"})) # Read data result = db.query({"goals": {}}) for goal in result["goals"]: print(goal["title"]) ``` -------------------------------- ### Implement Web Redirect Auth Flow Source: https://www.instantdb.com/llms-full.txt Example of using redirect-based authentication with InstantDB. ```jsx 'use client'; import React, { useState } from 'react'; import { init } from '@instantdb/react'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); const url = db.auth.createAuthorizationURL({ // Use the google client name in the Instant dashboard auth tab clientName: 'REPLACE_ME', redirectURL: window.location.href, }); import React from 'react'; export default function App() { return ( <> ); } function UserInfo() { const user = db.useUser(); return

Hello {user.email}!

; } function Login() { return Log in with Google; } ``` -------------------------------- ### Implement Google Sign-In in React Native Source: https://www.instantdb.com/docs/auth/google-oauth A complete example showing how to initialize InstantDB, configure Google Sign-In, and handle the authentication flow using an ID token. ```javascript import { View, Text, Button, StyleSheet } from 'react-native'; import { init } from '@instantdb/react-native'; import { GoogleSignin, GoogleSigninButton, } from '@react-native-google-signin/google-signin'; const APP_ID = '__APP_ID__'; const db = init({ appId: APP_ID }); GoogleSignin.configure({ // See https://react-native-google-signin.github.io/docs/original#configure iosClientId: 'YOUR_IOS_CLIENT_ID', }); function App() { return ( <> Loading...}> ); } function UserInfo() { const user = db.useUser(); return Hello {user.email}!; } function Login() { return ( { // 1. Sign in to Google await GoogleSignin.hasPlayServices(); const userInfo = await GoogleSignin.signIn(); const idToken = userInfo.data?.idToken; if (!idToken) { console.error('no ID token present!'); return; } // 2. Use your token, and sign into InstantDB! try { const res = await db.auth.signInWithIdToken({ // The unique name you gave the OAuth ``` -------------------------------- ### Log query result structure Source: https://www.instantdb.com/llms-full.txt Example output structure for a goal entity query. ```javascript console.log(data) { "goals": [ { "id": healthId, "title": "Get fit!" } ] } ``` -------------------------------- ### Custom update function usage Source: https://www.instantdb.com/llms-full.txt Example goal for a custom update function wrapper. ```typescript // Goal myCustomUpdate('todos', { dueDate: Date.now() }); ``` -------------------------------- ### Initialize a new InstantDB app Source: https://www.instantdb.com/llm-rules/AGENTS Creates a new application without local files, returning an app ID and admin token for environment configuration. ```bash npx instant-cli init-without-files --title ``` -------------------------------- ### Define file schema Source: https://www.instantdb.com/docs/storage Example schema definition for files including custom columns. ```javascript import { i } from "@instantdb/react"; const _schema = i.schema({ entities: { $files: i.entity({ path: i.string().unique().indexed(), isFavorite: i.boolean().optional() url: i.string(), }), }, }); ``` -------------------------------- ### Implement InstantDB Storage Operations Source: https://www.instantdb.com/llms-full.txt This example shows the full implementation of file uploading, querying the $files namespace for real-time image feeds, and deleting files via transactions. ```javascript 'use client'; import { init, InstaQLEntity } from '@instantdb/react'; import schema, { AppSchema } from '../instant.schema'; import React from 'react'; type InstantFile = InstaQLEntity const APP_ID = process.env.NEXT_PUBLIC_INSTANT_APP_ID; const db = init({ appId: APP_ID, schema }); // `uploadFile` is what we use to do the actual upload! // the `$files` will automatically update once the upload is complete async function uploadImage(file: File) { try { // Optional metadata you can set for uploads const opts = { // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type // Default: 'application/octet-stream' contentType: file.type, // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition // Default: 'inline' contentDisposition: 'attachment', }; await db.storage.uploadFile(file.name, file, opts); } catch (error) { console.error('Error uploading image:', error); } } function App() { // $files is the special namespace for querying storage data const { isLoading, error, data } = db.useQuery({ $files: { $: { order: { serverCreatedAt: 'asc' }, }, }, }); if (isLoading) { return null; } if (error) { return
Error fetching data: {error.message}
; } // The result of a $files query will contain objects with // metadata and a download URL you can use for serving files! const { $files: images } = data return (
Image Feed
Upload some images and they will appear below! Open another tab and see the changes in real-time!
); } interface SelectedFile { file: File; previewURL: string; } function ImageUpload() { const [selectedFile, setSelectedFile] = React.useState(null); const [isUploading, setIsUploading] = React.useState(false); const fileInputRef = React.useRef(null); const { previewURL } = selectedFile || {}; const handleFileSelect = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { const previewURL = URL.createObjectURL(file); setSelectedFile({ file, previewURL }); } }; const handleUpload = async () => { if (selectedFile) { setIsUploading(true); await uploadImage(selectedFile.file); URL.revokeObjectURL(selectedFile.previewURL); setSelectedFile(null); fileInputRef.current?.value && (fileInputRef.current.value = ''); setIsUploading(false); } }; return (
{isUploading ? (

Uploading...

) : previewURL && (
Preview
)}
); } function ImageGrid({ images }: { images: InstantFile[] }) { // Use `db.transact` to delete files const handleDelete = async (image: InstantFile) => { db.transact(db.tx.$files[image.id].delete()); } return (
{images.map((image) => { return (
{/* $files entities come with a `url` property */} {image.path}
{image.path} handleDelete(image)} className="cursor-pointer text-gray-300 px-1"> 𝘟
) })}
); } export default App; ```