Appwrite Web SDK

repository·main·Indexed 43 days ago

https://github.com/appwrite/sdk-for-web

A client-side library for integrating web applications with the Appwrite backend-as-a-service. Version 27.0.0 provides a type-safe interface to interact with services such as Authentication, Databases, and MFA via a REST API.

Tokens
76.6K
Snippets
244
Records
266
Agent score
56%

What's inside Appwrite

  1. Use Type Safety with Database Models

    main

    The SDK supports generic methods for database operations, allowing you to provide custom interfaces for full type safety in TypeScript or type hints in JavaScript.

    TypeScript

    Pass your interface as a generic parameter to methods like listDocuments or getDocument.

    JavaScript

    Use JSDoc @type annotations with Models.DocumentList<T> to enable IDE type hints.

    Tip: You can use the appwrite types command to automatically generate TypeScript interfaces from your Appwrite database schema.

    interface Book {
        name: string;
        author: string;
        releaseYear?: string;
        category?: string;
        genre?: string[];
        isCheckedOut: boolean;
    }
    
    const databases = new Databases(client);
    
    try {
        const documents = await databases.listDocuments<Book>(
            'your-database-id',
            'your-collection-id'
        );
        
        documents.documents.forEach(book => {
            console.log(`Book: ${book.name} by ${book.author}`); // Now you have full type safety
        });
    } catch (error) {
        console.error('Appwrite error:', error);
    }
  2. Initialize the Appwrite Web SDK

    main

    To use the Appwrite Web SDK, you must first initialize a Client instance by providing your API endpoint and your project ID. The endpoint is typically your Appwrite Cloud region URL or your self-hosted instance URL.

    1. Import Client from the appwrite package.
    2. Call .setEndpoint() with your API endpoint.
    3. Call .setProject() with your project ID.
    import { Client } from 'appwrite';
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
  3. Initialize the Appwrite SDK

    main

    To interact with Appwrite services, you must first initialize the Client with your project's endpoint and project ID. These credentials can be found in your Appwrite Console project settings.

    Note: Before initializing, ensure you have added your web platform (hostname) in the Appwrite Console to allow cross-domain communication.

    // Init your Web SDK
    const client = new Client();
    
    client
        .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
        .setProject('455x34dfkj') // Your project ID
    ;
  4. Install the Appwrite Web SDK

    main

    You can install the Appwrite Web SDK using NPM or via a CDN.

    Using NPM

    Install the package using your preferred package manager:

    npm install appwrite --save

    If you are using a bundler like Rollup or Webpack, import the required modules directly:

    import { Client, Account } from 'appwrite';

    Using CDN

    Add the following script tag to the bottom of your <body> tag before using any Appwrite services:

    <script src="https://cdn.jsdelivr.net/npm/appwrite@27.0.0"></script>
  5. Available Appwrite Services

    main

    The SDK provides specialized service classes to interact with different Appwrite modules. Each service requires an instance of Client passed to its constructor.

    Commonly used services include:

    • Account: Manage user authentication, sessions, and profiles.
    • Databases: Manage collections and documents.
    • Storage: Manage file uploads and downloads.
    • Functions: Execute server-side code.
    • Messaging: Handle push notifications and messaging.
    • Realtime: Subscribe to real-time events.
    • Avatars: Generate and manipulate user avatars.
    • Teams: Manage team memberships and permissions.
    • Presences: Track user presence in real-time.
    • Graphql: Execute GraphQL queries.
    • Organization: Manage organizational settings.
    • DocumentsDB, TablesDB, VectorsDB: Specialized database interfaces.
  6. Understand Large Number Handling with JSONbig

    main

    The Appwrite Web SDK uses JSONbig to handle large integers (64-bit integers) that exceed JavaScript's Number.MAX_SAFE_INTEGER.

    When parsing JSON responses, the SDK automatically converts large integers into JavaScript BigInt types if they fall within the 64-bit integer range, or keeps them as Number if they are within the safe integer range. This ensures data integrity for IDs and large numeric values.

  7. Build database queries with the Query class

    main

    The Query class provides a set of static methods to build complex search and filter criteria for Appwrite database requests. Each method returns a JSON-serialized string representing the query, which can then be passed to Appwrite SDK methods like databases.listDocuments.

    import { Query } from 'appwrite';
    
    // Example: Filtering documents where 'status' is 'active' and 'age' is greater than 18
    const queries = [
        Query.equal('status', 'active'),
        Query.greaterThan('age', 18)
    ];
    
    // These strings are passed to the SDK
    // console.log(queries);
  8. Manage transactions with DocumentsDB

    main

    The DocumentsDB service allows you to manage database transactions, which can be used to stage multiple operations and either commit or roll them back as a single unit. You can create transactions with an optional ttl (time-to-live) in seconds. Once a transaction is created, you can stage operations within it and then use updateTransaction to commit or rollback the changes.

    // Create a transaction with a 1-hour TTL
    const transaction = await documentsDB.createTransaction({ ttl: 3600 });
    
    // Stage operations (using createOperations)
    await documentsDB.createOperations({
        transactionId: transaction.$id,
        operations: [
            { /* operation 1 */ },
            { /* operation 2 }
        ]
    });
    
    // Commit the transaction
    await documentsDB.updateTransaction({
        transactionId: transaction.$id,
        commit: true
    });
  9. Use the Team and Membership models

    main

    Appwrite manages group access through Teams and Memberships.

    Team Model

    • name: The team name.
    • total: Total number of members.
    • prefs: Team-specific preferences.

    Membership Model

    Links a User to a Team.

    • teamId: The ID of the team.
    • userId: The ID of the user.
    • roles: An array of roles assigned to this user within the team.
    • joined: Date the user accepted the invitation.
  10. Understand Appwrite List Models

    main

    Appwrite uses specific list models to wrap collections of resources returned by query operations. Each list model contains a total number (the count of items matching the query) and an array of the actual resource objects. Common list types include:

    • DocumentList<Document>: For database documents.
    • RowList<Row>: For database rows.
    • TeamList<Team>: For team information.
    • SessionList: For user sessions.
    • FileList: For storage files.
    • ExecutionList: For function/site executions.
  11. Use Document and Row models for Database operations

    main

    When interacting with the Appwrite Database, resources follow the Document or Row structure. Both include system-level metadata prefixed with $.

    Document Model

    Used for collections. Includes:

    • $id: Document ID.
    • $collectionId: The collection this document belongs to.
    • $databaseId: The database this document belongs to.
    • $createdAt / $updatedAt: ISO 8601 timestamps.
    • $permissions: Array of permission strings.

    Row Model

    Used for tables. Includes:

    • $id: Row ID.
    • $sequence: Row sequence ID.
    • $tableId: The table this row belongs to.
    • $databaseId: The database this table belongs to.
    • $createdAt / $updatedAt: ISO 8601 timestamps.
    • $permissions: Array of permission strings.
  12. Understand the RealtimeResponseEvent structure

    main

    When a real-time event is received via a subscription callback, the payload follows the RealtimeResponseEvent<T> interface:

    • events: An array of event names (e.g., create, update, delete).
    • channels: An array of the channels that triggered the event.
    • timestamp: The ISO timestamp of the event.
    • payload: The actual data associated with the event (typed as T).
    • subscriptions: An array of backend-provided subscription IDs associated with this event.