initKeyManager
@niveth/key-manager
exports only one function that is initKeyManager
. initKeyManager
returns an object with keys
createUserAPIKey
- Use this to create newUser API Key
verifyUserAPIKey
- Use this to verify whether providedUser API Key
is valid and it has not exceeded ratelimitdeleteUserAPIKey
- Use this to delete aUser API Key
rotateUserAPIKey
- Use this to rotate aUser API Key
. Rotating a key will create a new key with sameid
androles
addRoles
- Use this to add roles to aUser API Key
removeRoles
- Use this to remove roles from aUser API Key
Type signature of initKeyManager
export type Endpoints<EndpointName extends string> = {
[name in EndpointName]: {
default: { maxReq: number; duration: number };
roles?: Record<string, { maxReq: number; duration: number }>;
};
};
export type InitKeyManagerOptions<EndpointName extends string> = {
rootAPIKey: string;
url?: string;
endpoints: Endpoints<EndpointName>;
};
export function initKeyManager<EndpointName extends string>({
rootAPIKey,
url = "https://key-manager.nivekithan.com",
endpoints,
}: InitKeyManagerOptions<EndpointName>);
It takes an object with keys
rootAPIKey
-string
,Root API Key
which you have copied from the websiteurl
(optional) -string
, If you have self hostedkey manager
then the url of your instance ofkey manager
. Make sure the url is in this formathttps://key-manager.nivekithan.com
, notice there is no trailing slash (/)endpoints
- Defineendpoints
you have to ratelimit and their ratelimits.
export type Endpoints<EndpointName extends string> = {
[name in EndpointName]: {
default: { maxReq: number; duration: number };
roles?: Record<string, { maxReq: number; duration: number }>;
};
};
endpoints
is an object with each key specifying the endpoint
name and corresponding value is an object with keys defaults
and roles?
.
default
- Its type signature is{maxReq : number; duration : number}
wheremaxReq
is maximum number of requests allowed forduration
in microseconds.roles
(optional) - Its type signature isRecord<string, {maxReq : number; duration : number}>
. Its an object withrole
as its keys and ratelimit as their values.
Example
Its recommended that you create a new file called keyManager.ts
in that initialize the key manager
.
1. Endpoint with different ratelimits per pricing plane
// keyManager.ts
import { initKeyManager } from "@niveth/key-manager";
export const {
verifyUserAPIKey,
createUserAPIKey,
addRoles,
deleteUserAPIKey,
removeRoles,
rotateUserAPIKey,
} = initKeyManager({
rootAPIKey: process.env.KEY_MANAGER_ROOT_KEY,
endpoints: {
CREATE_USER: {
default: { duration: 60_000, maxReq: 100 },
roles: {
PRO: { duration: 60_000, maxReq: 1000 },
TEAM: { duration: 60_000, maxReq: 5000 },
},
},
},
});
It initializes key manager
with a single endpoint CREATE_USER
. For FREE tier users it supports maximum 100 Requests
per 1 min
, for PRO tier users it supports maximum 1000 Requests
per 1 min
and for TEAM tier users it supports maximum 5000 requests
per 1 min