UNPKG

@trycourier/courier-js

Version:

A browser-safe API wrapper

254 lines (193 loc) 7.23 kB
# `@trycourier/courier-js` The base API client and shared instance singleton for Courier's JavaScript Browser SDK. ## Installation ```sh npm install @trycourier/courier-js ``` ## Usage Setup an API client. ### `CourierClient` A simple api client wrapper for all supported Courier endpoints and sockets. ```ts const courierClient = new CourierClient({ userId: 'some_user_id', // The user id for your user. This is usually the user id you maintain in your system for a user. jwt: 'ey...n0', // The access token associated with the user. tenantId: 'asdf', // [OPTIONAL] Allows you to scope a client to a specific tenant. If you didn't configure multi-tenant routing, you probably don't need this. showLogs: true, // [OPTIONAL] Shows debugging logs from the client. Defaults to process.env.NODE_ENV === 'development'. }); ``` ### `Courier.shared...` A singleton instance of the `CourierClient` and other logic used to authenticate a single user across multiple requests, websockets, and more. ```ts Courier.shared.signIn({ userId: 'some_user_id', // The user id for your user. This is usually the user id you maintain in your system for a user. jwt: 'ey...n0', // The access token associated with the user. tenantId: 'asdf', // [OPTIONAL] Allows you to scope a client to a specific tenant. If you didn't configure multi-tenant routing, you probably don't need this. showLogs: true, // [OPTIONAL] Shows debugging logs from the client. Defaults to process.env.NODE_ENV === 'development'. }); Courier.shared.signOut(); Courier.shared.addAuthenticationListener(({ userId }) => { console.log(userId); }); ``` ## Authentication To use the SDK, you need to generate a JWT (JSON Web Token) for your user. **This JWT should always be generated by your backend server, never in client-side code.** **How it works:** 1. **Your frontend calls your backend:** - When your app needs to authenticate a user, your frontend should make a request to your own backend (e.g., `/api/generate-courier-jwt`). 2. **Your backend calls Courier to issue a JWT:** - In your backend endpoint, use your [Courier API Key](https://app.courier.com/settings/api-keys) to call the [Courier JWT Token Endpoint](https://www.courier.com/docs/reference/auth/issue-token) and generate a JWT for the user. - Your backend then returns the JWT to your frontend. **Example: Quick Testing with cURL** To quickly test JWT generation (for development only), you can use the following cURL command to call Courier's API directly. **Do not use this in production or from client-side code.** ```sh curl --request POST \ --url https://api.courier.com/auth/issue-token \ --header 'Accept: application/json' \ --header 'Authorization: Bearer $YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data \ '{ "scope": "user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", "expires_in": "$YOUR_NUMBER days" }' ``` ### Inbox APIs Read and update user inbox messages. ```ts // Fetch the inbox messages for the user const inboxMessages = await courierClient.inbox.getMessages(); // Fetch the archived messages for the user const archivedMessages = await courierClient.inbox.getArchivedMessages(); // Click a message await courierClient.inbox.click({ messageId: '1-678...', // The message id. (Example: inboxMessages.data.messages.nodes[0].messageId) trackingId: 'u2602...', // The tracking id. (Example: inboxMessages.data.messages.nodes[0].trackingIds.clickTrackingId) }); // Read a message await courierClient.inbox.read({ messageId: '1-678...', }); // Unread a message await courierClient.inbox.unread({ messageId: '1-678...', }); // Open a message await courierClient.inbox.open({ messageId: '1-678...', }); // Archive a message await courierClient.inbox.archive({ messageId: '1-678...', }); // Unarchive a message await courierClient.inbox.unarchive({ messageId: '1-678...', }); // Read all messages await courierClient.inbox.readAll(); // Archive read messages await courierClient.inbox.archiveRead(); // Archive all messages await courierClient.inbox.archiveAll(); ``` ### Preferences APIs Read and update user notification preferences. ```ts // Get list of preferences const preferences = await courierClient.preferences.getUserPreferences(); // Get a preference topic const topic = await courierClient.preferences.getUserPreferenceTopic({ topicId: 'HVS...' }); // Update a preference topic const topic = await courierClient.preferences.putUserPreferenceTopic({ topicId: 'HVS...', status: 'OPTED_IN', // 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED' hasCustomRouting: true, // true | false customRouting: ['inbox', 'push'], // Array of: 'direct_message' | 'inbox' | 'email' | 'push' | 'sms' | 'webhook' }); ``` ### Brands APIs Read data about a brand. ```ts // Gets a brand by id const brand = await courierClient.brands.getBrand({ brandId: 'YF1...' }); ``` ### Lists APIs Read and update user list details. ```ts // Subscribes to a list await courierClient.lists.putSubscription({ listId: 'your_list_id' }); // Unsubscribes from a list await courierClient.lists.deleteSubscription({ listId: 'your_list_id' }); ``` ### Models #### Inbox ```ts export interface InboxMessage { messageId: string; title?: string; body?: string; preview?: string; actions?: InboxAction[]; data?: Record<string, any>; created?: string; archived?: string; read?: string; opened?: string; tags?: string[]; trackingIds?: { archiveTrackingId?: string; openTrackingId?: string; clickTrackingId?: string; deliverTrackingId?: string; unreadTrackingId?: string; readTrackingId?: string; }; } export interface InboxAction { content?: string; href?: string; data?: Record<string, any>; background_color?: string; style?: string; } ``` #### Preferences ```ts export interface CourierUserPreferencesTopic { topicId: string; topicName: string; sectionId: string; sectionName: string; status: CourierUserPreferencesStatus; defaultStatus: CourierUserPreferencesStatus; hasCustomRouting: boolean; customRouting: CourierUserPreferencesChannel[]; } export type CourierUserPreferencesStatus = 'OPTED_IN' | 'OPTED_OUT' | 'REQUIRED' | 'UNKNOWN'; export type CourierUserPreferencesChannel = 'direct_message' | 'inbox' | 'email' | 'push' | 'sms' | 'webhook' | 'unknown'; ``` #### Brands ```ts export interface CourierBrand { id: string; name: string; created: number; updated: number; published: number; version: string; settings?: CourierBrandSettings; } ``` See more endpoints that aren't in this SDK in the [Courier API Reference](https://www.courier.com/docs/reference/intro). # **Share feedback with Courier** We want to make this the best SDK for managing notifications! Have an idea or feedback about our SDKs? Let us know! [Courier Web Issues](https://github.com/trycourier/courier-web/issues)