Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

Clerk Node.js SDK

Set up Clerk Node.js

Create a Clerk application

You need to create a Clerk application in your Clerk Dashboard before you can set up Clerk Node.js. For more information, check out our Set up your application guide.

Install @clerk/clerk-sdk-node

Once a Clerk application has been created, you can install and then start using Clerk Node.js in your application. An ESM module for the Clerk Node SDK is available under the @clerk/clerk-sdk-node(opens in a new tab) npm package.

terminal
npm install @clerk/clerk-sdk-node
terminal
yarn add @clerk/clerk-sdk-node
terminal
pnpm add @clerk/clerk-sdk-node

Set environment variables

Below is an example of an .env.local file.

Pro tip! If you are signed into your Clerk Dashboard, your secret key should become visible by clicking on the eye icon. Otherwise, you can find your keys in the Clerk Dashboard on the API Keys(opens in a new tab) page.

.env.local
CLERK_SECRET_KEY={{secret}}

Available methods

All resource operations are mounted as sub-APIs on the clerkClient object. To access the resource operations, you must first instantiate a clerkClient instance.

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

import { sessions } from '@clerk/clerk-sdk-node'; import Cookies from 'cookies'; // Retrieve the particular session ID from a // query string parameter const sessionId = req.query._clerk_session_id; // Note: Clerk stores the clientToken in a cookie // named "__session" for Firebase compatibility const cookies = new Cookies(req, res); const clientToken = cookies.get('__session'); 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.

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

Last updated on April 19, 2024

What did you think of this content?

Clerk © 2024