Knock Javascript client library
A client-side Javascript library to interact with user-facing Knock features, such as feeds.
Note: this is a lower level library designed for building UI on top of
Documentation
See the documentation for usage examples.
Installation
Via NPM:
npm install @knocklabs/client
Via Yarn:
yarn add @knocklabs/client
Configuration
To configure the client library you will need:
- A public API key (found in the Knock dashboard)
- A feed channel ID (found in the Knock dashboard)
- A user ID, and optionally an auth token for production environments
import Knock from "@knocklabs/client";
const knockClient = new Knock(process.env.KNOCK_API_KEY);
knockClient.authenticate(
currentUser.id,
currentUser.knockToken,
);
Usage
You can find an example usage in a React application in the example/App.js file, which is a plain-old Create React App.
Retrieving new items from the feed
import Knock from "@knocklabs/client";
const knockClient = new Knock(process.env.KNOCK_API_KEY);
knockClient.authenticate(currentUser.id, currentUser.knockToken);
const feedClient = knockClient.feeds.initialize(
process.env.KNOCK_FEED_CHANNEL_ID,
);
const teardown = feedClient.listenForUpdates();
feedClient.on("messages.new", ({ entries }) => {
console.log(entries);
});
feedClient.fetch({
status: "all" | "unread" | "unseen",
after: lastItem.__cursor,
before: firstItem.__cursor,
page_size: 10,
source: "notification-key",
tenant: "jurassic-park",
});
teardown();
Reading the feed store state (programmatically)
const feedClient = knockClient.feeds.initialize(
process.env.KNOCK_FEED_CHANNEL_ID,
);
const { items } = feedClient.store.getState();
Reading the feed store state (in React)
import create from "zustand";
const feedClient = knockClient.feeds.initialize(
process.env.KNOCK_FEED_CHANNEL_ID,
);
const useFeedStore = create(feedClient.store);
const items = useFeedStore((state) => state.items);
const meta = useFeedStore((state) => state.metadata);
Marking items as read, seen, or archived
const feedClient = knockClient.feeds.initialize(
process.env.KNOCK_FEED_CHANNEL_ID,
);
feedClient.markAsRead(feedItemOrItems);
feedClient.markAsSeen(feedItemOrItems);
feedClient.markAsArchived(feedItemOrItems);
feedClient.markAsUnread(feedItemOrItems);
feedClient.markAsUnseen(feedItemOrItems);
feedClient.markAsUnarchived(feedItemOrItems);
Managing user preferences
await knockClient.preferences.set({
channel_types: { email: true, sms: false },
workflows: {
"dinosaurs-loose": {
channel_types: { email: false, in_app_feed: true },
},
},
});
const preferences = await knockClient.preferences.get();
await knockClient.preferences.setChannelType("email", false);
await knockClient.preferences.setWorkflow("dinosaurs-loose", {
channel_types: {
email: true,
in_app_feed: false,
},
});