Javascript SDK API Reference

Complete API reference for the Knock Javascript SDK.

In this section, you'll find the documentation for the classes and methods available in the @knocklabs/client library.

Knock

The top-level Knock class, used to interact with a client instance.

Params:

apiKeystring*The public API key for the Knock environment.
optionsKnockOptionsAdditional options to pass through.

Example:

userId

Returns the user ID of the authenticated user.

Returns: string

feeds

Returns a FeedClient instance that can be initialized to return a feed.

Optionally a feed can be initialized with a default set of FeedClientOptions which will be applied to all subsequent requests.

Returns: Feed instance

Example:

user

Returns a UserClient instance to interact with the users API for the current, authenticated user.

Returns: UserClient instance

Example:

preferences

Returns a Preferences instance to interact with the preferences API for the current, authenticated user.

Returns: Preferences instance

Example:

client

Returns an instance of an authenticated ApiClient that can be used to make HTTP and Websocket requests to Knock.

Returns: ApiClient instance

authenticate

Authenticates the current user and creates a new Knock session.

Params:

userIdstring*The authenticated user to retrieve a feed for
userTokenstringJWT for the authenticated user. Not required in development environments.
optionsAuthenticateOptionsAdditional options to authenticate your Knock user with.

Returns: void

Example:

teardown

Tears down a current session and disconnects any connected sockets.

Returns: void


ApiClient

The API client exposes direct functions for communicating with the Knock API over HTTP and websocket.

socket

Returns: a Socket


FeedClient

initialize

Creates a new Feed instance.

teardownInstances

Tears down any current feed instances.

reinitializeInstances

Reinitializes any current feed instances by reconnecting their realtime connections.


Feed

Represents the connection between a user and a feed, including methods for interacting with the items on that feed. Also includes a stateful store that can be used to build in-app notification experiences easily. See FeedStoreState for more on the shape of the store.

store

Returns: StoreApi<FeedStoreState>

listenForUpdates

Connects the feed instance to the realtime socket so that any new items published to the feed are received over the websocket.

Returns: void

Example:

on

Binds an event handler to be invoked when the event is triggered.

Events:

items.received.realtimeeventInvoked whenever items are received in realtime from the socket.
items.received.pageeventInvoked whenever items are received from performing a fetch. Will be invoked for the initial fetch as well.
items.archivedeventInvoked when one or more items are archived.
items.unarchivedeventInvoked when one or more items are unarchived.
items.seeneventInvoked when one or more items are seen.
items.unseeneventInvoked when one or more items are unseen.
items.readeventInvoked when one or more items are read.
items.unreadeventInvoked when one or more items are unread.

Params:

eventNameenum of `messages.new` | `items.received.realtime` | `items.received.page` | `items.received.*`The type of event to bind to.
callbackfunctionA function to be invoked when the event is triggered.

Returns: void.

Example:

off

Unbinds an existing event handler previously bound with on. Use this method to cleanup bound event handlers.

Returns: void.

getState

Programmatically access the current FeedStoreState.

Returns: FeedStoreState.

markAllAsSeen

Marks all of the items in the store optimistically as seen and performs a server-side request to mark all items on the feed in the current scope as seen. Broadcasts a items:all_seen event.

Please note: this operation is deferred and may take some time to process all items in the feed.

Returns: Promise<ApiResponse>

markAsSeen

Marks the given items as seen. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAsUnseen

Removes the seen status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAllAsRead

Marks all of the items in the store optimistically as read and performs a server-side request to mark all items on the feed in the current scope as read. Broadcasts a items:all_read event.

Please note: this operation is deferred and may take some time to process all items in the feed.

Returns: Promise<ApiResponse>

markAsRead

Sets the read status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAsUnread

Removes the read status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAllAsArchived

Marks all of the items in the store optimistically as archived and performs a server-side request to mark all items on the feed in the current scope as archived. Broadcasts a items:all_archived event.

Please note: this operation is deferred and may take some time to process all items in the feed.

Returns: Promise<ApiResponse>

markAsArchived

Sets the archived status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState. Broadcasts a items:archived event.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAsUnarchived

Removes the archived status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.

Returns: Promise<ApiResponse>

markAsInteracted

Sets the interacted status on the item or items given. Will perform the operation optimistically, including updating the current metadata in the FeedStoreState. Broadcasts an items:interacted event.

Params:

itemOrItemsFeedItemOrItemsA single `FeedItem` or a list of `FeedItem` to perform the update on.
metadataRecord<string, any>Additional metadata to be stored with the interaction event.

Returns: Promise<ApiResponse>

fetch

Fetches

Emits items.received.page events on a successful fetch.

Params:

optionsFetchFeedOptionsOptions to pass through to the feed request

Returns: Promise<ApiResponse>

fetchNextPage

Fetches the next page of the feed items (if there are any more to fetch).

Emits items.received.page events on a successful fetch.

Note: this will apply any current feed filters and append returned items to the end of the current set of items.


UserClient

get

Retrieves the current, authenticated user by calling the get user endpoint directly from the client.

Returns: Promise<ApiResponse>

Example:

identify

Identifies a user by calling the identify user endpoint directly from the client.

Params:

propertiesobjectAn object of key-value pairs for attributes you want to associate with the user.

Returns: Promise<ApiResponse>

Example:

getAllPreferences

Retrieves all preferences for the authenticated user by calling the get preferences endpoint directly from the client.

Returns: Promise<ApiResponse>

Example:

getPreferences

Retrieves a preference set for the authenticated user by calling the get preferences endpoint directly from the client.

preferenceSetStringThe preference set from Knock
tenantString (optional)The tenant from Knock

Returns: Promise<ApiResponse>

Example:

setPreferences

Updates the authenticated user's preferences by calling the set preferences endpoint directly from the client.

Params:

preferenceSetSetPreferencesPropertiesThe preferences to set for the current user.

Returns: Promise<ApiResponse>

Example:

getChannelData

Retrieves channel data for the authenticated user by calling the get channel data endpoint directly from the client.

channelIdStringThe channel ID from Knock

Returns: Promise<ApiResponse>

Example:

setChannelData

Updates the channel data for the current user by calling the set channel data endpoint directly from the client.

Params:

channelIdStringThe channel ID to update the channel data for
channelDataAnyThe data to update for the channel data

Returns: Promise<ApiResponse>

Example:

Preferences

get

Retrieves a preference set for the authenticated user by calling the get preferences endpoint directly from the client.

Returns: Promise<ApiResponse>

Example:

set

Updates the authenticated users preferences by calling the set preferences endpoint directly from the client.

Params:

preferenceSetSetPreferencesPropertiesThe preferences to set for the current user.

Returns: Promise<ApiResponse>

Example:

Types

KnockOptions

hoststringA base URL to use for all API requests to Knock
logLevel'debug' | nullWhen set to debug, will output log events

AuthenticateOptions

Options to pass through to the authenticate method.

onUserTokenExpiring(oldToken: string) => Promise<string | void>A callback to provide that will fire before a user Token expires. By default will fire 30s before the token is set to expire. If a string is returned from the resolved promise, that will be used as the new user token.
timeBeforeExpirationInMsnumberDetermines the amount of time in milliseconds before the token expires that the callback should be fired.

FeedStoreState

A zustand state store that holds the current feed state, including item counts, for easy notification feed rendering within your application. The FeedStoreState is entirely managed by the Feed instance, and any calls to fetch(), markAsX, or fetchNextPage will update the state accordingly.

itemsFeedItem[]An ordered list of feed items to be rendered.
pageInfoPageInfoThe page info of the last successful fetch.
metadataFeedMetadataThe current feed metadata including unread, unseen, read, and total counts of items in the feed.
loadingbooleanWhether or not the feed is currently loading.
networkStatusNetworkStatusRepresents the various network states the feed can be in, including differentiating between 'fetching more' and 'fetching'.