Skip to content

Commit

Permalink
Update clerk express SDK docs
Browse files Browse the repository at this point in the history
  • Loading branch information
EmmanouelaPothitou committed Jul 9, 2024
1 parent 00656c9 commit e8f92b1
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 56 deletions.
2 changes: 1 addition & 1 deletion docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -1769,7 +1769,7 @@
"href": "/docs/references/express/token-verification"
},
{
"title": "Migrating from Clerk Node SDK to Clerk Express",
"title": "Migrating from Clerk Node SDK to Clerk Express SDK",
"href": "/docs/references/express/migrate-from-node-to-express"}
]
]
Expand Down
20 changes: 9 additions & 11 deletions docs/references/express/available-methods.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ If you would like to use the default instance of `clerkClient` provided by the S
```

```js
const pkg = require('@clerk/express');
const clerkClient = pkg.default;
const { clerkClient } = require('@clerk/express');
clerkClient.sessions
.getSessionList()
Expand Down Expand Up @@ -49,13 +48,13 @@ const clientList = await clerkClient.clients.getClientList();
```

```js
const Clerk = require('@clerk/clerk-sdk-node/cjs/instance').default;
const { createClerkClient } = require('@clerk/express/cjs');
const clerkClient = Clerk({ secretKey: '{{secret}}' });
const clerkClient = createClerkClient({ secretKey: '{{secret}}' });
clerkClient.sessions
.getSessionList()
.then((sessions) => console.log(sessions))
clerkClient.clients
.getClientList()
.then((clientList) => console.log(clientList))
.catch((error) => console.error(error));
```
</CodeBlockTabs>
Expand All @@ -72,10 +71,9 @@ The following options are available for you to customize the behaviour of the `c
| Option | Description | Default | Environment variable |
| --- | --- | --- | --- |
| `secretKey` | Server key for `api.clerk.com`. Can be found in your Clerk Dashboard on the **[API Keys](https://dashboard.clerk.com/last-active?path=api-keys)** page. | none | `CLERK_SECRET_KEY` |
| `apiVersion` | API version to use | `v4` | `CLERK_API_VERSION` |
| `apiUrl` | For debugging | `https://api.clerk.com` | `CLERK_API_URL` |
| `httpOptions` | HTTP client options | `{}` | N/A |
| `secretKey` (required) | Server key for `api.clerk.com`. Can be found in your Clerk Dashboard on the **[API Keys](https://dashboard.clerk.com/last-active?path=api-keys)** page. | none | `CLERK_SECRET_KEY` |
| `apiVersion?` | API version to use | `v4` | `CLERK_API_VERSION` |
| `apiUrl?` | For debugging | `https://api.clerk.com` | `CLERK_API_URL` |
{/* TODO: I think more of a description and example can be added for httpOptions. Also, we need to add information for audience, proxyUrl, jwtKey, publishableKey, domain, isSallite, telemetry */}
Expand Down
17 changes: 9 additions & 8 deletions docs/references/express/migrate-from-node-to-express.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
---
title: Clerk Express.js SDK
description: Learn how to migrate from Node.js to Express.js.
title: Clerk Express SDK
description: Learn how to migrate from Clerk Node SDK to Express SDK.
---

# Clerk Express.js SDK
# Clerk Express SDK

## Migrating from Clerk Node SDK to Clerk Express
## Migrating from Clerk Node SDK to Clerk Express SDK

<Steps>

Expand Down Expand Up @@ -51,18 +51,18 @@ You can find an example [here](/docs/backend-requests/handling/nodejs#clerk-expr
- **Centralized Middleware:**
Use `clerkMiddleware` to authenticate all incoming requests without blocking them. This middleware will handle the handshake mechanism.
- **Require Authentication in Specific Routes or Handlers:**
Use `requireAuth()` to enforce authentication on specific routes. This middleware returns an HTTP 401 response for unauthenticated request.
Use `requireAuth` to enforce authentication on specific routes. This middleware returns an HTTP 401 response for unauthenticated request.
```js
const express = require('express');
const { clerkMiddleware, requireAuth } = require('@clerk/clerk-express');
const { clerkMiddleware, requireAuth } = require('@clerk/express');

const app = express();

// Apply centralized middleware
app.use(clerkMiddleware());

// Define a protected route
app.get('/protected', requireAuth(), (req, res) => {
app.get('/protected', requireAuth, (req, res) => {
res.send('This is a protected route');
});

Expand All @@ -84,9 +84,10 @@ To access the authentication state within your routes or handlers, use `getAuth(
```jsx

const express = require('express');
const { getAuth } = require('@clerk/clerk-express');
const { clerkMiddleware, getAuth } = require('@clerk/express');

const app = express();
app.use(clerkMiddleware())

app.get('/auth-state', (req, res) => {
const authState = getAuth(req);
Expand Down
21 changes: 12 additions & 9 deletions docs/references/express/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ pnpm add @clerk/express

### Set environment variables

Below is an example of an `.env.local` file.
The developers have to load the environment variables from the .env.local file by using dotenv or any other library of their preference.
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](https://dashboard.clerk.com/last-active?path=api-keys) page.

Expand All @@ -52,22 +53,24 @@ CLERK_SECRET_KEY={{secret}}

All resource operations are mounted as sub-APIs on the `clerkClient` object. To access the resource operations, [you must first instantiate a `clerkClient` instance](/docs/references/express/available-methods).

## 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.

## Error handling

Express SDK functions throw errors (`ClerkAPIResponseError`) when something goes wrong. You'll need to catch them in a `try/catch` block and handle them gracefully. For example:

```ts filename="example.ts"
import { clerkClient } from '@clerk/express';

try {
const res = await someBackendApiCall();
const userList = await clerkClient.users.getUserList();
} catch (error) {
// Error handling
}
```

> See the guide on [using Clerk with Express.js](/docs/backend-requests/handling/nodejs#express-error-handlers) to learn about Express error handling.
### Express error handlers

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 in the [Express error handling guide](https://expressjs.com/en/guide/error-handling.html). An example error handler can be found above.

If you are using the strict middleware variant, the `err` passed to your error handler will contain enough context for you to respond as you deem fit.
30 changes: 3 additions & 27 deletions docs/references/express/token-verification.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,7 @@ Clerk's JWT session token can be verified in a networkless manner using the JWT

To learn more about Clerk's token verification, you can find more information on our guide to [validating session tokens](/docs/backend-requests/handling/manual-jwt).

The value of the JWT verification key can also be added on the instance level or on any single middleware call e.g. for Next.js.

```js
import { withAuth } from '@clerk/nextjs';

const handler = (req, res) => {
// ...
};

withAuth(handler, { jwtKey: 'my_clerk_public_key' });
```
The value of the JWT verification key can also be added at the instance level or for any single middleware call.

Custom instance initialization:

Expand All @@ -31,20 +21,7 @@ const clerk = createClerkClient({ jwtKey: 'my_clerk_public_key' });

## Validate the authorized party of a session token

Clerk's JWT session token contains the `azp` claim, which equals the Origin of the request during token generation. You can provide the middlewares with a list of allowlisted origins to verify against, to protect your application of the subdomain cookie leaking attack. You can find an example below:

<CodeBlockTabs type="framework" options={["Next.js", "Node"]}>
```js
import { requireAuth } from '@clerk/nextjs';

const authorizedParties = ['http://localhost:3000', 'https://example.com']

function handler(req: RequireAuthProp<NextApiRequest>, res: NextApiResponse) {
// do something with the auth attribute
}

export requireAuth(handler, { authorizedParties });
```
Clerk's JWT session token contains the `azp` claim, which equals the Origin of the request during token generation. You can provide the middleware with a list of allowlisted origins to verify against, to protect your application from subdomain cookie leaking attacks. You can find an example below:

```js
// Express app
Expand All @@ -53,5 +30,4 @@ import { clerkMiddleware } from '@clerk/express';
const authorizedParties = ['http://localhost:3000', 'https://example.com'];

app.use(clerkMiddleware({ authorizedParties }));
```
</CodeBlockTabs>
```

0 comments on commit e8f92b1

Please sign in to comment.