GetStream JS SDK

repository·main·Indexed 43 days ago

https://github.com/getstream/stream-js

The official low-level JavaScript client for GetStream.io (version 8.15.0), used to build scalable newsfeeds and activity streams in Node.js, the browser, and React Native. It provides tools for managing activities, follow relations, and users, with support for real-time subscriptions via Faye and TypeScript generics for type-safe data models.

Tokens
14.8K
Snippets
64
Records
68
Agent score
56%

What's inside GetStream

  1. How to use the API client in a browser environment

    main

    The SDK includes a security check that throws an error if it detects a secret being used in a browser environment. If you are running backend code in environments like Google Cloud that might be misidentified, or if you explicitly need to bypass this check, set browser: false in the options object.

    const client = connect('YOUR_API_KEY', 'API_KEY_SECRET', 'APP_ID', { browser: false });
  2. Install the Stream JS SDK by downloading JS files

    main

    You can manually download the SDK files and host them yourself. You can choose between the standard JS version or the minified version for production environments.

    Standard JS: https://raw.githubusercontent.com/GetStream/stream-js/main/dist/js/getstream.js
    Minified JS: https://raw.githubusercontent.com/GetStream/stream-js/main/dist/js_min/getstream.js
  3. Initialize the API client in the Browser

    main

    For client-side (web/mobile) usage, you must never expose your API_KEY_SECRET. Instead, generate a user token on your server using client.createUserToken(userId) and pass that token to the connect function in the browser along with your API_KEY and APP_ID.

    // 1. SERVER-SIDE: Generate token
    import { connect } from 'getstream';
    const serverClient = connect('YOUR_API_KEY', 'API_KEY_SECRET');
    const userToken = serverClient.createUserToken('the-user-id');
    
    // 2. BROWSER-SIDE: Initialize client with token
    import { connect } from 'getstream';
    const client = connect('apikey', userToken, 'appid');
  4. Subscribe to real-time feed changes

    main

    Stream uses Faye for real-time notifications. You can subscribe to a feed to receive updates whenever it changes. The subscribe method returns a subscription object with a .cancel() method to stop listening.

    // client must be initialized with a userToken for browser use
    const client = connect('YOUR_API_KEY', userToken, 'APP_ID');
    const user1 = client.feed('user', '1');
    
    const subscription = user1.subscribe((data) => {
      console.log('Feed updated:', data);
    });
    
    // Later, to stop listening:
    subscription.cancel();
  5. Install the Stream JS SDK via JS Delivr CDN

    main

    For direct browser usage without a build step, you can include the SDK via the JS Delivr CDN.

    Warning: Always pin a specific version to avoid breaking changes in your application caused by automatic updates to the latest version.

    <!-- Recommended: Pin a specific version to prevent breaking changes -->
    <script src="https://cdn.jsdelivr.net/npm/getstream@8.0.0/dist/js_min/getstream.js"></script>
    
    <!-- Avoid using the unpinned version in production -->
    <script src="https://cdn.jsdelivr.net/npm/getstream/dist/js_min/getstream.js"></script>
  6. Use Stream JS with React Native

    main

    The getstream package can be integrated into React Native applications.

    Security Note: Never expose your App Secret in mobile apps, browsers, or any other non-trusted environments. The App Secret should only be used on your backend server.

  7. Manage follow relations

    main

    You can manage relationships between feeds using follow, unfollow, followMany, and unfollowMany.

    • follow(type, id, options): Follow a feed. Use { limit: 0 } to follow without copying history.
    • unfollow(type, id, options): Unfollow a feed. Use { keepHistory: true } to keep previously published activities.
    • followMany(follows): Batch create follow relations (Server-side only).
    const user1 = client.feed('user', '1');
    
    // Follow a feed
    user1.follow('flat', '42');
    
    // Follow without copying history
    user1.follow('flat', '42', { limit: 0 });
    
    // Unfollow while keeping history
    user1.unfollow('flat', '42', { keepHistory: true });
    
    // List followers/following
    user1.followers({ limit: '10', offset: '10' });
    user1.following({ limit: '10', offset: '0' });
  8. Use Stream with TypeScript

    main

    The SDK supports generics to provide type safety for your specific data models (Users, Activities, Collections, etc.). You can pass a custom StreamType interface to connect to ensure all subsequent calls like .user(), .feed(), and .collections.get() are typed correctly.

    import { connect, EnrichedActivity, NotificationActivity } from 'getstream';
    
    type MyStreamType = {
      userType: { name: string; username: string };
      activityType: { text: string };
      // ... other types
    };
    
    const client = connect<MyStreamType>('api_key', 'secret!', 'app_id');
    
    // Typed feed access
    const timeline = client.feed('timeline', 'feed_id');
    timeline.get().then((response) => {
      // response.results is typed as EnrichedActivity<MyStreamType>*
      const activities = response.results as EnrichedActivity<MyStreamType>[];
    });
  9. Initialize the API client in Node.js

    main

    To use the SDK on the server side, use the connect function with your API_KEY and API_KEY_SECRET. You can optionally provide an APP_ID and an options object to specify the location (data center) and timeout (in milliseconds).

    import { connect } from 'getstream';
    
    // Basic instantiation
    const client = connect('YOUR_API_KEY', 'API_KEY_SECRET');
    
    // Advanced instantiation with app ID and options
    const client = connect('YOUR_API_KEY', 'API_KEY_SECRET', 'APP_ID', { 
      location: 'us-east', 
      timeout: 15000 
    });
  10. Manage activities in a feed

    main

    Use the feed method to get a feed object, then use various methods to manage activities. All API calls are asynchronous and return a Promise.

    Common Feed Operations:

    • get({ limit, offset, id_lt, ... }): Retrieve activities with pagination or filters.
    • addActivity(activity): Add a single activity.
    • addActivities(activities): Add multiple activities at once.
    • removeActivity(id | { foreign_id }): Remove an activity by its ID or its foreign_id.
    • updateActivityToTargets(...): Update the to field (targets) of an existing activity (Server-side only).
    const user1 = client.feed('user', '1');
    
    // Get activities with pagination
    user1.get({ limit: 5, offset: 5 }).then(body => console.log(body));
    
    // Add an activity
    user1.addActivity({
      actor: 1,
      verb: 'tweet',
      object: 1,
      foreign_id: 'tweet:1'
    });
    
    // Remove an activity by foreign_id
    user1.removeActivity({ foreign_id: 'tweet:1' });
  11. How Collections and CollectionEntry work together

    main

    The Collections class acts as a manager for all collection operations within a specific Stream client and token. It provides methods to interact with entire collections (like add, get, update, delete, and batch operations like upsertMany).

    When you retrieve a specific item using Collections.get(), it returns a CollectionEntry object. A CollectionEntry is a specialized instance representing a single item within a collection. It allows you to perform operations directly on that specific item (e.g., entry.update(), entry.delete()) without needing to pass the collection name and ID again. This pattern provides a more object-oriented way to manage individual data entries.

    // 1. Use Collections to get a specific entry
    const entry = await collections.get("food", "cheese101");
    
    // 2. Use the entry directly to perform actions
    await entry.update({ name: "new cheese burger" });
    await entry.delete();