Search…
Getting started with Node

Before you get started

Set CLERK_API_KEY

The Node SDK will pick automatically the CLERK_API_KEY vale 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 above variable.
Make sure you update **** this variable with the API key found in your dashboard under SettingsAPI Keys.
.env.local
1
CLERK_API_KEY=test_asdf1234
Copied!
For detailed usage to the official documentation of the Node SDK.
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 middlewares 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.

Node.js middleware

Optional session

This strategy allows you to detect whether or not there's an active session, and handle each case separately.
Javascript
Typescript
1
import { withAuth } from '@clerk/clerk-sdk-node';
2
3
function handler(req, res) {
4
if (req.session) {
5
// do something with session.userId
6
} else {
7
// Respond with 401 or similar
8
}
9
}
10
11
export default withAuth(handler);
Copied!
1
import { withAuth, WithAuthProp } from '@clerk/clerk-sdk-node';
2
3
function handler(req: WithAuthProp<NextApiRequest>, res: NextApiResponse) {
4
if (req.session) {
5
// do something with session.userId
6
} else {
7
// Respond with 401 or similar
8
}
9
}
10
11
export withAuth(handler);
Copied!

Required session

This strategy mandates that a session be available. If not, it returns a 401 (no body) and your handler is never called.
Javascript
Typescript
1
import { requireAuth } from '@clerk/clerk-sdk-node';
2
3
function handler(req, res) {
4
// do something with session.userId
5
}
6
7
export default requireAuth(handler)
Copied!
1
import { requireAuth, RequireAuthProp } from '@clerk/clerk-sdk-node';
2
3
function handler(req: RequireAuthProp<NextApiRequest>, res: NextApiResponse) {
4
// do something with session.userId
5
}
6
7
export default requireAuth(handler)
Copied!

Express middleware

For usage with Express, this package also exports ClerkExpressWithSession (lax) & ClerkExpressRequireSession (strict) middlewares that can be used in the standard manner:
1
import { ClerkExpressWithAuth } from '@clerk/clerk-sdk-node';
2
3
// Initialize Express app the usual way
4
// Then add Clerk middleware
5
app.use(ClerkExpressWithAuth());
Copied!
The ClerkExpressWithSession middleware will set the Clerk session on the request object as req.session and then call the next middleware.
You can then implement your own logic for handling a logged-in or logged-out user in your express endpoints or custom middleware, depending on whether your users are trying to access a public or protected resource.
If you want to use the express middleware of your custom Clerk instance, you can use:
1
app.use(clerk.expressWithSession());
Copied!
Where clerk is your own instance.
If you prefer that the middleware renders a 401 (Unauthenticated) itself, you can use the following variant instead:
1
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node';
2
3
app.use(ClerkExpressRequireAuth());
Copied!

onError option

The Express middleware supports an options object as an optional argument. The only key currently supported is onError for providing your own error handler.
The onError function, if provided, should take an Error argument (onError(error)).
Depending on the return value, it can affect the behavior of the middleware as follows:
  • If an Error is returned, the middleware will call next(err) with that error. If the err has a statusCode it will indicate to Express what HTTP code the response should have.
  • If anything other than an Error is returned (or nothing is returned at all), then the middleware will call next() without arguments
The default implementations unless overridden are:
1
// defaultOnError swallows the error
2
defaultOnError(error: Error) {
3
console.error(error.message);
4
}
5
6
// strictOnError returns the error so that Express will halt the request chain
7
strictOnError(error: Error) {
8
console.error(error.message);
9
return error;
10
}
Copied!
defaultOnError is used in the lax middleware variant and strictOnError in the strict variant.

Express Error Handlers

Not to be confused with the onError option mentioned above, Express comes with a default error handler for errors encountered in the middleware chain.
Developers can also implement their own custom error handlers as detailed here.
An example error handler can be found in the Express examples folder:
1
// Note: this is just a sample errorHandler that pipes clerk server errors through to your API responses
2
// You will want to apply different handling in your own app to avoid exposing too much info to the client
3
function errorHandler(err, req, res, next) {
4
const statusCode = err.statusCode || 500;
5
const body = err.data || { error: err.message };
6
7
res.status(statusCode).json(body);
8
}
Copied!
If you are using the strict middleware variant, the err pass to your error handler will contain enough context for you to respond as you deem fit.

Optional session

This strategy allows you to detect whether or not there's an active session, and handle each case separately
1
import { ClerkExpressWithAuth } from '@clerk/clerk-sdk-node';
2
3
//
4
// Initialize express app
5
//
6
7
app.use(ClerkExpressWithAuth());
Copied!

Required session

This strategy mandates that a session be available. If not, it returns a 401 (no body) and your handler is never called.
1
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node';
2
3
//
4
// Initialize express app
5
//
6
7
app.use(ClerkExpressRequireAuth());
Copied!

Manual authentication

Authenticate a particular session

Highly recommended for authenticating actions.
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);
Copied!

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);
Copied!
Last modified 1mo ago