Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev
Check out a preview of our new docs.

Getting started with Node SDK

Installation

An ES module for the Clerk Node SDK is available under the @clerk/clerk-sdk-node npm package. Use `npm` or `yarn` to install the Clerk Node module.

1
npm install @clerk/clerk-sdk-node
1
yarn add @clerk/clerk-sdk-node

Set CLERK_SECRET_KEY

The Node SDK will automatically pick the CLERK_SECRET_KEY value from your environment variables. If your application is using .env files, create a file named .env.local in your application root if it doesn't exist already, and add the below variable:

.env
1

Make sure you update this variable with the API key found in your Clerk instance dashboard under API Keys

Resource types

The following types are of interest to the integrator:

ResourceDescription
Clientunique browser or mobile app
Sessiona session for a given user on a given client
Usera person signed up via Clerk
Emailan email message sent to another user
SMS Messagean SMS message sent to another user

The following types are not directly manipulable but can be passed as params to applicable calls:

ResourceDescriptionUsage
EmailAddressemail address, a user may have a primary & several secondaryemail address id can be provided to `emails` sub-api to specify the recipient
PhoneNumberE.164 telephone number, a user may have a primary & several secondaryphone number id can be provided to `smsMessages` sub-api to specify the recipient

Internal implementation details

This SDK is written in TypeScript.

CJS, ESM, and UMD module builds are provided.

All resource operations are mounted as sub-APIs on a Clerk class and return promises that either resolve with their expected resource types or reject with the error types described below.

The sub-APIs are also importable directly if you don't want to go through the Clerk class.

Available options and ENV vars

The following options are available for you to customize the behaviour of the Clerk class.

Note that most options can also be set as ENV vars so that you don't need to pass anything to the constructor or set it via the available setters.

OptionDescriptionDefaultENV variable
secretKeyserver key for api.clerk.devnone`CLERK_SECRET_KEY`
apiVersionfor future use, v1 for now"v1"`CLERK_API_VERSION`
serverApiURLfor debugging / future use"https://api.clerk.dev"`CLERK_API_URL`
httpOptionshttp client options{}N/A

For every option the resolution is as follows, in order of descending precedence:

  1. option passed
  2. ENV var (if applicable)
  3. default

Another available environment variable is CLERK_LOGGING.

You can set its value to true to enable additional logging that may be of use when debugging an issue.

Singleton

If you are comfortable with setting the CLERK_SECRET_KEY ENV variable and be done with it, the default instance created by the SDK will suffice for your needs.

ESM

import clerk from '@clerk/clerk-sdk-node';
const userList = await clerk.users.getUserList();

Or if you are interested only in a certain resource:

import { sessions } from '@clerk/clerk-sdk-node';
const sessionList = await sessions.getSessionList();

CJS

const pkg = require('@clerk/clerk-sdk-node');
const clerk = pkg.default;
clerk.emails
.createEmail({ fromEmailName, subject, body, emailAddressId })
.then((email) => console.log(email))
.catch((error) => console.error(error));

Or if you prefer a resource sub-api directly:

const pkg = require('@clerk/clerk-sdk-node');
const { clients } = pkg;
clients
.getClient(clientId)
.then((client) => console.log(client))
.catch((error) => console.error(error));

Setters

The following setters are available for you to change the options even after you've obtained a handle on a Clerk or sub-api instance:

If you have a clerk handle:

  • clerk.secretKey = value;
  • clerk.serverApiUrl = value;
  • clerk.apiVersion = value;
  • clerk.httpOptions = value;

If are using a sub-api handle and wish to change options on the (implicit) singleton Clerk instance:

  • setClerkSecretKey(value)
  • setClerkServerApiUrl(value)
  • setClerkApiVersion(value)
  • setClerkHttpOptions(value)

Custom instantiation

ESM

import Clerk from '@clerk/clerk-sdk-node/esm/instance';
const clerk = new Clerk({ secretKey: 'secret_key' });
const clientList = await clerk.clients.getClientList();

CJS

const Clerk = require('@clerk/clerk-sdk-node/cjs/instance').default;
const clerk = new Clerk({ secretKey: 'secret_key' });
clerk.smsMessages
.createSMSMessage({ message, phoneNumberId })
.then((smsMessage) => console.log(smsMessage))
.catch((error) => console.error(error));

Multi-session applications

If Clerk is running in multi-session mode, it's important to ensure your frontend sends the Session ID that is making the request.

Our middleware will look for a query string parameter named _clerk_session_id. If this parameter is not found, the middleware will instead choose the last active session, which may be subject to race conditions and should not be relied on for authenticating actions.

Connect/Express middlewares

The Clerk Node SDK offers two middlewares to authenticate your backend endpoints.

Manual authentication

Authenticate a particular session

1
import { sessions } from '@clerk/clerk-sdk-node';
2
import Cookies from 'cookies';
3
4
// Retrieve the particular session ID from a
5
// query string parameter
6
const sessionId = req.query._clerk_session_id;
7
8
// Note: Clerk stores the clientToken in a cookie
9
// named "__session" for Firebase compatibility
10
const cookies = new Cookies(req, res);
11
const clientToken = cookies.get('__session');
12
13
const session = await sessions.verifySession(sessionId, clientToken);

Authenticate the last active session

Using the last active session is appropriate when determining the user after a navigation.

1
import { clients, sessions } from '@clerk/clerk-sdk-node';
2
3
// Note: Clerk stores the clientToken in a cookie
4
// named "__session" for Firebase compatibility
5
const cookies = new Cookies(req, res);
6
const clientToken = cookies.get('__session');
7
8
const client = await clients.verifyClient(sessionToken);
9
const sessionId = client.lastActiveSessionId;
10
11
const session = await sessions.verifySession(sessionId, clientToken);

Was this helpful?

Clerk © 2023