Appwrite Node.js SDK

repository·main·Indexed 42 days ago

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

The Appwrite Node.js SDK (node-appwrite v29.0.0) allows developers to integrate Appwrite's open-source backend services, such as Databases, Users, and Storage, into server-side Node.js applications. It provides a REST API abstraction with support for TypeScript generics and JSDoc type hints, as well as comprehensive account management features including MFA, OAuth2, and session handling.

Tokens
302.6K
Snippets
843
Records
897
Agent score
52%

What's inside Appwrite

  1. Use Type Hints with JSDoc in JavaScript

    main

    In plain JavaScript, you can achieve IDE type hints by using JSDoc to define your model and casting the result of service methods to Models.DocumentList<T>.

    /**
     * @typedef {Object} Book
     * @property {string} name
     * @property {string} author
     * @property {string} [releaseYear]
     * @property {string} [category]
     * @property {string[]} [genre]
     * @property {boolean} isCheckedOut
     */
    
    const databases = new Databases(client);
    
    try {
        /** @type {Models.DocumentList<Book>} */
        const documents = await databases.listDocuments(
            'your-database-id',
            'your-collection-id'
        );
        
        documents.documents.forEach(book => {
            console.log(`Book: ${book.name} by ${book.author}`); // Type hints available
        });
    } catch (error) {
        console.error('Appwrite error:', error);
    }
  2. Configure the Appwrite Node.js SDK Client

    main

    To use the SDK, you must first initialize a Client instance by providing your API endpoint, project ID, and a secret API key. This client is then passed to service classes like Messaging to authenticate requests.

    const sdk = require('node-appwrite');
    
    const client = new sdk.Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>') // Your project ID
        .setKey('<YOUR_API_KEY>'); // Your secret API key
  3. Use Type Safety with Models in TypeScript

    main

    The SDK supports generic methods for database operations like listDocuments and getDocument. By passing a custom interface as a generic type parameter, you can ensure full type safety for your document models.

    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}`); // Full type safety
        });
    } catch (error) {
        console.error('Appwrite error:', error);
    }
  4. Initialize the Appwrite Node.js SDK

    main

    To use the Appwrite Node.js SDK, you must first initialize a Client instance by providing your API endpoint, project ID, and an optional session for user authentication. Once the client is configured, you can instantiate specific service classes (like Apps) by passing the client instance to their constructor.

    Required configuration:

    • setEndpoint(endpoint): Your Appwrite API endpoint (e.g., https://cloud.appwrite.io/v1).
    • setProject(projectId): Your unique project ID.
    • setSession(session): (Optional) The user session string used to authenticate requests as a specific user.
    const sdk = require('node-appwrite');
    
    const client = new sdk.Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>') // Your project ID
        .setSession(''); // The user session to authenticate with
    
    const apps = new sdk.Apps(client);
  5. Initialize the Appwrite Node.js SDK client

    main

    To use any Appwrite service, you must first initialize a Client instance. You need to provide your API endpoint, your project ID, and a secret API key (which should be kept secure and never exposed to the client-side).

    Required Configuration:

    • setEndpoint(endpoint): The URL of your Appwrite instance (e.g., https://cloud.appwrite.io/v1).
    • setProject(projectId): Your unique project identifier.
    • setKey(apiKey): Your secret API key used for server-side authentication.
    const sdk = require('node-appwrite');
    
    const client = new sdk.Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
        .setProject('<YOUR_PROJECT_ID>')
        .setKey('<YOUR_API_KEY>');
  6. Initialize the Appwrite Client

    main

    To interact with Appwrite, you must first initialize a Client instance. You need to provide your API endpoint, your project ID, and a session string for authentication.

    • setEndpoint(endpoint): Sets your Appwrite API endpoint (e.g., https://cloud.appwrite.io/v1).
    • setProject(projectId): Sets your unique project ID.
    • setSession(session): Sets the user session string to authenticate the request.
    const sdk = require('node-appwrite');
    
    const client = new sdk.Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
        .setProject('<YOUR_PROJECT_ID>')
        .setSession('<YOUR_SESSION>');
  7. Use Document and Row models for Database operations

    main

    Appwrite uses Document and Row types to represent data within databases.

    • Document: Represents a record in a collection. It includes system metadata like $id, $collectionId, $databaseId, $createdAt, $updatedAt, and $permissions.
    • Row: Represents a record in a table. It includes $id, $sequence, $tableId, $databaseId, $createdAt, $updatedAt, and $permissions.

    For ease of use with dynamic data, you can use DefaultDocument or DefaultRow, which extend the base models with a catch-all indexer ([key: string]: any) to allow access to custom attributes.

  8. Understand Appwrite Insights and Reports

    main

    Appwrite generates Reports to analyze system performance, accessibility, or database health. Reports contain multiple Insights.

    Insights

    An Insight provides a specific finding with a severity (info, warning, critical) and a status (active, dismissed).

    Insights include Call-to-Action (CTA) buttons (InsightCTA) that allow developers to resolve issues directly via the SDK. A CTA contains:

    • service: The SDK namespace to invoke (e.g., databases, tablesDB, documentsDB, or vectorsDB).
    • method: The specific method to call.
    • params: An object containing the parameters required for that method (e.g., databaseId, collectionId).

    Reports

    Reports are categorized (e.g., performance, accessibility) and target a specific resource via targetType and target (e.g., a URL for Lighthouse or a resource ID for a database).

  9. Understand OAuth2 Flows and Grant Models

    main

    Appwrite supports several OAuth2 flows, including standard Authorization Code, Device Authorization, and Pushed Authorization Requests (PAR).

    Key OAuth2 Models:

    • Oauth2Grant: Represents a user's consent to an application. Includes requested scopes, resources, and authorizationDetails (as a JSON string).
    • Oauth2Token: The result of a successful token request. Contains the access_token, refresh_token, token_type, and optionally an id_token (if the openid scope was granted).
    • Oauth2DeviceAuthorization: Used for device flows (e.g., CLI or Smart TVs). Provides a user_code for the user to enter on a separate device and a device_code for the client to poll the token endpoint.
    • Oauth2PAR: Pushed Authorization Requests. Provides a request_uri to handle the authorization request.
  10. Use the Query class to filter and search data

    main

    The Query class provides a set of static methods used to construct query strings for filtering, searching, sorting, and paginating resources in Appwrite. Each static method returns a JSON-serialized string representing the query operation. These strings are typically passed as an array to SDK methods like databases.listDocuments().

    import { Query } from 'node-appwrite';
    
    // Example: Filtering documents where 'status' is 'active' and 'age' is greater than 18
    const queries = [
        Query.equal('status', 'active'),
        Query.greaterThan('age', 18),
        Query.orderAsc('$createdAt')
    ];
  11. Handle User Sessions and Identities

    main

    Appwrite distinguishes between a Session (the active connection/authentication state) and an Identity (the link to an external provider).

    • Session: Contains information about the current active session, including userId, expire date, provider, and device metadata (IP, OS, client type). It also includes a current boolean to indicate if it is the active session.
    • Identity: Represents the user's identity from an external provider (e.g., Google, GitHub), containing the providerUid and provider-specific access/refresh tokens.