Gathering detailed insights and metrics for @knocklabs/node
Gathering detailed insights and metrics for @knocklabs/node
Gathering detailed insights and metrics for @knocklabs/node
Gathering detailed insights and metrics for @knocklabs/node
Official Node SDK for interacting with the Knock API
npm install @knocklabs/node
Typescript
Module System
TypeScript (97.4%)
Shell (1.46%)
JavaScript (1.14%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Apache-2.0 License
43 Stars
145 Commits
7 Forks
5 Watchers
29 Branches
13 Contributors
Updated on Jul 10, 2025
Latest Version
1.11.0
Package Id
@knocklabs/node@1.11.0
Unpacked Size
1.63 MB
Size
261.30 kB
File Count
845
Published on
Jul 10, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
This library provides convenient access to the Knock REST API from server-side TypeScript or JavaScript.
The REST API documentation can be found on docs.knock.app. The full API of this library can be found in api.md.
It is generated with Stainless.
1npm install @knocklabs/node
The full API of this library can be found in api.md.
1import Knock from '@knocklabs/node'; 2 3const client = new Knock({ 4 apiKey: process.env['KNOCK_API_KEY'], // This is the default and can be omitted 5}); 6 7const response = await client.workflows.trigger('dinosaurs-loose', { 8 recipients: ['dnedry'], 9 data: { dinosaur: 'triceratops' }, 10}); 11 12console.log(response.workflow_run_id);
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
1import Knock from '@knocklabs/node';
2
3const client = new Knock({
4 apiKey: process.env['KNOCK_API_KEY'], // This is the default and can be omitted
5});
6
7const user: Knock.User = await client.users.get('dnedry');
Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
When the library is unable to connect to the API,
or if the API returns a non-success status code (i.e., 4xx or 5xx response),
a subclass of APIError
will be thrown:
1const user = await client.users.get('dnedry').catch(async (err) => { 2 if (err instanceof Knock.APIError) { 3 console.log(err.status); // 400 4 console.log(err.name); // BadRequestError 5 console.log(err.headers); // {server: 'nginx', ...} 6 } else { 7 throw err; 8 } 9});
Error codes are as follows:
Status Code | Error Type |
---|---|
400 | BadRequestError |
401 | AuthenticationError |
403 | PermissionDeniedError |
404 | NotFoundError |
422 | UnprocessableEntityError |
429 | RateLimitError |
>=500 | InternalServerError |
N/A | APIConnectionError |
Certain errors will be automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default.
You can use the maxRetries
option to configure or disable this:
1// Configure the default for all requests: 2const client = new Knock({ 3 maxRetries: 0, // default is 2 4}); 5 6// Or, configure per-request: 7await client.users.get('dnedry', { 8 maxRetries: 5, 9});
Requests time out after 1 minute by default. You can configure this with a timeout
option:
1// Configure the default for all requests:
2const client = new Knock({
3 timeout: 20 * 1000, // 20 seconds (default is 1 minute)
4});
5
6// Override per-request:
7await client.users.get('dnedry', {
8 timeout: 5 * 1000,
9});
On timeout, an APIConnectionTimeoutError
is thrown.
Note that requests which time out will be retried twice by default.
List methods in the Knock API are paginated.
You can use the for await … of
syntax to iterate through items across all pages:
1async function fetchAllUsers(params) { 2 const allUsers = []; 3 // Automatically fetches more pages as needed. 4 for await (const user of client.users.list()) { 5 allUsers.push(user); 6 } 7 return allUsers; 8}
Alternatively, you can request a single page at a time:
1let page = await client.users.list(); 2for (const user of page.entries) { 3 console.log(user); 4} 5 6// Convenience methods are provided for manually paginating: 7while (page.hasNextPage()) { 8 page = await page.getNextPage(); 9 // ... 10}
The "raw" Response
returned by fetch()
can be accessed through the .asResponse()
method on the APIPromise
type that all methods return.
This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.
You can also use the .withResponse()
method to get the raw Response
along with the parsed data.
Unlike .asResponse()
this method consumes the body, returning once it is parsed.
1const client = new Knock(); 2 3const response = await client.users.get('dnedry').asResponse(); 4console.log(response.headers.get('X-My-Header')); 5console.log(response.statusText); // access the underlying Response object 6 7const { data: user, response: raw } = await client.users.get('dnedry').withResponse(); 8console.log(raw.headers.get('X-My-Header')); 9console.log(user.id);
[!IMPORTANT] All log messages are intended for debugging only. The format and content of log messages may change between releases.
The log level can be configured in two ways:
KNOCK_LOG
environment variablelogLevel
client option (overrides the environment variable if set)1import Knock from '@knocklabs/node'; 2 3const client = new Knock({ 4 logLevel: 'debug', // Show all log messages 5});
Available log levels, from most to least verbose:
'debug'
- Show debug messages, info, warnings, and errors'info'
- Show info messages, warnings, and errors'warn'
- Show warnings and errors (default)'error'
- Show only errors'off'
- Disable all loggingAt the 'debug'
level, all HTTP requests and responses are logged, including headers and bodies.
Some authentication-related headers are redacted, but sensitive data in request and response bodies
may still be visible.
By default, this library logs to globalThis.console
. You can also provide a custom logger.
Most logging libraries are supported, including pino, winston, bunyan, consola, signale, and @std/log. If your logger doesn't work, please open an issue.
When providing a custom logger, the logLevel
option still controls which messages are emitted, messages
below the configured level will not be sent to your logger.
1import Knock from '@knocklabs/node'; 2import pino from 'pino'; 3 4const logger = pino(); 5 6const client = new Knock({ 7 logger: logger.child({ name: 'Knock' }), 8 logLevel: 'debug', // Send all messages to pino, allowing it to filter 9});
This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.
The SDK provides functionality to sign authentication tokens for client-side requests, such as for in-app feeds. This feature requires the jose
package as an optional peer dependency.
If you plan to use JWT token signing, you'll need to install jose
:
1npm install jose 2# or 3yarn add jose
1import Knock from '@knocklabs/node'; 2 3// Generate a JWT token for a user 4const token = await Knock.signUserToken('user-1');
You can provide specific grants to control access to different resources:
1import { signUserToken, buildUserTokenGrant, Grants } from '@knocklabs/node'; 2 3const token = await signUserToken('user-1', { 4 // Token valid for 12 hours (43200 seconds) 5 expiresInSeconds: 43200, 6 // Grants for tenant and object access 7 grants: [ 8 // Grant access to a tenant 9 buildUserTokenGrant({ type: 'tenant', id: 'tenant-id' }, [Grants.SlackChannelsRead]), 10 // Grant access to specific objects 11 buildUserTokenGrant({ type: 'object', id: 'object-id', collection: 'videos' }, [ 12 Grants.ChannelDataRead, 13 Grants.ChannelDataWrite, 14 ]), 15 ], 16});
For more examples and detailed documentation about token signing, see the token signing examples and visit Knock's Authentication Documentation.
To make requests to undocumented endpoints, you can use client.get
, client.post
, and other HTTP verbs.
Options on the client, such as retries, will be respected when making these requests.
1await client.post('/some/path', { 2 body: { some_prop: 'foo' }, 3 query: { some_query_arg: 'bar' }, 4});
To make requests using undocumented parameters, you may use // @ts-expect-error
on the undocumented
parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you
send will be sent as-is.
1client.workflows.trigger({ 2 // ... 3 // @ts-expect-error baz is not yet public 4 baz: 'undocumented option', 5});
For requests with the GET
verb, any extra params will be in the query, all other requests will send the
extra param in the body.
If you want to explicitly send an extra argument, you can do so with the query
, body
, and headers
request
options.
To access undocumented response properties, you may access the response object with // @ts-expect-error
on
the response object, or cast the response object to the requisite type. Like the request params, we do not
validate or strip extra properties from the response from the API.
By default, this library expects a global fetch
function is defined.
If you want to use a different fetch
function, you can either polyfill the global:
1import fetch from 'my-fetch'; 2 3globalThis.fetch = fetch;
Or pass it to the client:
1import Knock from '@knocklabs/node'; 2import fetch from 'my-fetch'; 3 4const client = new Knock({ fetch });
If you want to set custom fetch
options without overriding the fetch
function, you can provide a fetchOptions
object when instantiating the client or making a request. (Request-specific options override client options.)
1import Knock from '@knocklabs/node'; 2 3const client = new Knock({ 4 fetchOptions: { 5 // `RequestInit` options 6 }, 7});
To modify proxy behavior, you can provide custom fetchOptions
that add runtime-specific proxy
options to requests:
Node [docs]
1import Knock from '@knocklabs/node'; 2import * as undici from 'undici'; 3 4const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); 5const client = new Knock({ 6 fetchOptions: { 7 dispatcher: proxyAgent, 8 }, 9});
Bun [docs]
1import Knock from '@knocklabs/node'; 2 3const client = new Knock({ 4 fetchOptions: { 5 proxy: 'http://localhost:8888', 6 }, 7});
Deno [docs]
1import Knock from 'npm:@knocklabs/node';
2
3const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
4const client = new Knock({
5 fetchOptions: {
6 client: httpClient,
7 },
8});
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an issue with questions, bugs, or suggestions.
TypeScript >= 4.9 is supported.
The following runtimes are supported:
"node"
environment ("jsdom"
is not supported at this time).Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
17 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
2 existing vulnerabilities detected
Details
Reason
branch protection is not maximal on development and all release branches
Details
Reason
Found 5/13 approved changesets -- score normalized to 3
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More