From ffa5a1e41adad6a6b80a5d94b011db529ad45474 Mon Sep 17 00:00:00 2001 From: LekoArts Date: Thu, 9 Jan 2025 15:40:59 +0100 Subject: [PATCH 01/11] update manifest --- docs/manifest.json | 13 +++++++++++++ docs/manifest.schema.json | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/manifest.json b/docs/manifest.json index 02a8a792a0..cc84bf893a 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -2444,6 +2444,19 @@ ] ] }, + { + "title": "Fastify", + "collapse": true, + "icon": "fastify", + "items": [ + [ + { + "title": "Overview", + "href": "/docs/references/fastify/overview" + } + ] + ] + }, { "title": "React Router", "collapse": true, diff --git a/docs/manifest.schema.json b/docs/manifest.schema.json index 3773be9eef..e685a2fab2 100644 --- a/docs/manifest.schema.json +++ b/docs/manifest.schema.json @@ -140,7 +140,8 @@ "vue", "x", "expo", - "nuxt" + "nuxt", + "fastify" ] } } From 8411434d78017d778697324cdb6ea8ec03d759ac Mon Sep 17 00:00:00 2001 From: LekoArts Date: Thu, 9 Jan 2025 15:41:10 +0100 Subject: [PATCH 02/11] update main /docs page --- docs/index.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/index.mdx b/docs/index.mdx index 0645869ca2..e73330293a 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -113,6 +113,12 @@ Find all the guides and resources you need to develop with Clerk. --- + - [Fastify](/docs/quickstarts/fastify) + - Quickly add authentication and user management to your Fastify application. + - {} + + --- + - [SDKs](/docs/references/overview) - Clerk's SDKs allow you to call the Clerk server API without having to implement the calls yourself. - {} From f87a69e27bf621b6f03ed0367616ce03f69777bc Mon Sep 17 00:00:00 2001 From: LekoArts Date: Thu, 9 Jan 2025 15:41:26 +0100 Subject: [PATCH 03/11] add reference doc --- docs/quickstarts/fastify.mdx | 56 +--------- docs/references/fastify/overview.mdx | 147 +++++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 55 deletions(-) create mode 100644 docs/references/fastify/overview.mdx diff --git a/docs/quickstarts/fastify.mdx b/docs/quickstarts/fastify.mdx index 9e146a2029..c7f65e061a 100644 --- a/docs/quickstarts/fastify.mdx +++ b/docs/quickstarts/fastify.mdx @@ -82,7 +82,7 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic The `clerkPlugin` is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin` to handle all routes or limit it to specific ones. - The following example registers the plugin for all routes. To register the plugin for specific routes only, refer to the [**Using Clerk for specific pages only**](/docs/quickstarts/fastify#using-clerk-for-specific-routes-only) section. + The following example registers the plugin for all routes. To register the plugin for specific routes only, refer to the [**Using Clerk for specific pages only**](/docs/references/fastify/overview#configure-clerk-plugin-for-specific-routes){{ target: '_blank' }} section. > [!IMPORTANT] > The `dotenv/config` module must be imported before any Clerk modules. This order is important because Clerk instances are created during the import process and rely on environment variables, such as API keys, to be initialized correctly. For more information, refer to the [Fastify docs](https://fastify.dev/docs/latest/Guides/Getting-Started/#loading-order-of-your-plugins). @@ -149,57 +149,3 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic start() ``` - -## Configure `clerkPlugin` for specific routes - -If you want to use Clerk for specific pages only, you can register the plugin for specific routes. In the following example, the routes are split into protected and public routes. - -```ts {{ filename: 'index.ts' }} -import 'dotenv/config' -import Fastify, { FastifyPluginCallback } from 'fastify' -import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' - -const fastify = Fastify({ logger: true }) - -const protectedRoutes: FastifyPluginCallback = (instance, options, done) => { - instance.register(clerkPlugin) - - instance.get('/protected', async (request, reply) => { - const { userId } = getAuth(request) - - // Protect the route from unauthenticated users - if (!userId) { - return reply.code(403).send({ message: 'Access denied. Authentication required.' }) - } - - const user = await clerkClient.users.getUser(userId) - - // Only authenticated users will see the following message - reply.send({ message: 'This is a protected route.', user }) - }) - - done() -} - -const publicRoutes: FastifyPluginCallback = (instance, options, done) => { - instance.get('/', async (request, reply) => { - reply.send({ message: 'This is a public route.' }) - }) - - done() -} - -fastify.register(protectedRoutes) -fastify.register(publicRoutes) - -const start = async () => { - try { - await fastify.listen({ port: 8080 }) - } catch (error) { - fastify.log.error(error) - process.exit(1) - } -} - -start() -``` diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx new file mode 100644 index 0000000000..83d7313223 --- /dev/null +++ b/docs/references/fastify/overview.mdx @@ -0,0 +1,147 @@ +--- +title: Fastify SDK +description: Learn how to integrate Clerk into your Fastify application using the Clerk Fastify SDK. +--- + +The Clerk Fastify SDK is the recommended method for integrating Clerk into your Express application. + +See the [quickstart](/docs/quickstarts/fastify) to get started. + +## Methods + +### `clerkPlugin()` + +The `clerkPlugin()` is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin` to handle all routes or limit it to specific ones. + +The `clerkPlugin()` function checks the request's cookies and headers for a session JWT and if found, attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. + +```ts +// dotenv must be imported before @clerk/fastify +import "dotenv/config"; +import Fastify from "fastify"; +import { clerkPlugin } from '@clerk/fastify' + +const fastify = Fastify({ logger: true }); + +fastify.register(clerkPlugin); +``` + +You can also pass options to the plugin: + +```ts +import "dotenv/config"; +import Fastify from "fastify"; +import { clerkClient, clerkPlugin, getAuth } from "@clerk/fastify"; + +const fastify = Fastify({ logger: true }); + +fastify.register(clerkPlugin, { + hookName: "preHandler" +}); +``` + +#### Options + +The `clerkPlugin()` function accepts [these options](/docs/references/backend/overview) plus the following: + + + - `hookName` + - `'onRequest' | 'preHandler'` + + Decide on which of Fastify's [request/reply hooks](https://fastify.dev/docs/latest/Reference/Hooks/#requestreply-hooks) Clerk should run. Default: `'preHandler'` + + +### `getAuth()` + +The following example uses [`getAuth()`](/docs/references/nextjs/get-auth){{ target: '_blank' }} to retrieve the `userId`, which is used to protect the route and is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the current user's `User` object. + +```ts +import 'dotenv/config' +import Fastify from 'fastify' +import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' + +const fastify = Fastify({ logger: true }) + +fastify.register(clerkPlugin) + +fastify.get('/', async (request, reply) => { + const { userId } = getAuth(request) + + // Protect the route from unauthenticated users + if (!userId) { + return reply.code(403).send({ error: 'Unauthorized request.' }) + } + + const user = userId ? await clerkClient.users.getUser(userId) : null + + return reply.send({ + message: 'User retrieved successfully.', + user, + }) +}) + +const start = async () => { + try { + await fastify.listen({ port: 8080 }) + } catch (error) { + fastify.log.error(error) + process.exit(1) + } +} + +start() +``` + +## Configure `clerkPlugin()` for specific routes + +If you want to use Clerk for specific pages only, you can register the plugin for specific routes. In the following example, the routes are split into protected and public routes. + +```ts {{ filename: 'index.ts' }} +import 'dotenv/config' +import Fastify, { FastifyPluginCallback } from 'fastify' +import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' + +const fastify = Fastify({ logger: true }) + +const protectedRoutes: FastifyPluginCallback = (instance, options, done) => { + instance.register(clerkPlugin) + + instance.get('/protected', async (request, reply) => { + const { userId } = getAuth(request) + + // Protect the route from unauthenticated users + if (!userId) { + return reply.code(403).send({ message: 'Access denied. Authentication required.' }) + } + + const user = await clerkClient.users.getUser(userId) + + // Only authenticated users will see the following message + reply.send({ message: 'This is a protected route.', user }) + }) + + done() +} + +const publicRoutes: FastifyPluginCallback = (instance, options, done) => { + instance.get('/', async (request, reply) => { + reply.send({ message: 'This is a public route.' }) + }) + + done() +} + +fastify.register(protectedRoutes) +fastify.register(publicRoutes) + +const start = async () => { + try { + await fastify.listen({ port: 8080 }) + } catch (error) { + fastify.log.error(error) + process.exit(1) + } +} + +start() +``` From ce71b21a6f84eed179a54a7f25e8427437331a8c Mon Sep 17 00:00:00 2001 From: LekoArts Date: Thu, 9 Jan 2025 15:51:08 +0100 Subject: [PATCH 04/11] formatting --- docs/references/fastify/overview.mdx | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index 83d7313223..7083e22bb5 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -17,27 +17,27 @@ The `clerkPlugin()` function checks the request's cookies and headers for a sess ```ts // dotenv must be imported before @clerk/fastify -import "dotenv/config"; -import Fastify from "fastify"; +import 'dotenv/config' +import Fastify from 'fastify' import { clerkPlugin } from '@clerk/fastify' -const fastify = Fastify({ logger: true }); +const fastify = Fastify({ logger: true }) -fastify.register(clerkPlugin); +fastify.register(clerkPlugin) ``` You can also pass options to the plugin: ```ts -import "dotenv/config"; -import Fastify from "fastify"; -import { clerkClient, clerkPlugin, getAuth } from "@clerk/fastify"; +import 'dotenv/config' +import Fastify from 'fastify' +import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' -const fastify = Fastify({ logger: true }); +const fastify = Fastify({ logger: true }) fastify.register(clerkPlugin, { - hookName: "preHandler" -}); + hookName: 'preHandler', +}) ``` #### Options From eda1863467bb936b627e3e59f1670fa5cc04c8d1 Mon Sep 17 00:00:00 2001 From: vi Date: Mon, 13 Jan 2025 12:35:08 -0500 Subject: [PATCH 05/11] edit --- docs/references/fastify/overview.mdx | 48 +++++++++++++++------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index 7083e22bb5..016e91ab4b 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -1,19 +1,19 @@ --- -title: Fastify SDK +title: Clerk Fastify SDK description: Learn how to integrate Clerk into your Fastify application using the Clerk Fastify SDK. --- -The Clerk Fastify SDK is the recommended method for integrating Clerk into your Express application. +The Clerk Fastify SDK is the recommended method for integrating Clerk into your Express application. Refer to the [quickstart guide](/docs/quickstarts/fastify) to get started. -See the [quickstart](/docs/quickstarts/fastify) to get started. ## Methods ### `clerkPlugin()` -The `clerkPlugin()` is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin` to handle all routes or limit it to specific ones. +The `clerkPlugin()` is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid and if valid, attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. You can configure it to handle all routes or limit it to specific ones. -The `clerkPlugin()` function checks the request's cookies and headers for a session JWT and if found, attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. + +#### Example: Register `clerkPlugin()` ```ts // dotenv must be imported before @clerk/fastify @@ -26,34 +26,35 @@ const fastify = Fastify({ logger: true }) fastify.register(clerkPlugin) ``` -You can also pass options to the plugin: - -```ts -import 'dotenv/config' -import Fastify from 'fastify' -import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' +### Configure `clerkPlugin()` -const fastify = Fastify({ logger: true }) - -fastify.register(clerkPlugin, { - hookName: 'preHandler', -}) -``` +The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) and the following additional options: -#### Options +You can also pass options to the plugin: -The `clerkPlugin()` function accepts [these options](/docs/references/backend/overview) plus the following: - `hookName` - `'onRequest' | 'preHandler'` - Decide on which of Fastify's [request/reply hooks](https://fastify.dev/docs/latest/Reference/Hooks/#requestreply-hooks) Clerk should run. Default: `'preHandler'` + Determines which of Fastify's [Request/Reply hooks](https://fastify.dev/docs/latest/Reference/Hooks/#requestreply-hooks) Clerk should run. Default: `'preHandler'` +#### Example: Pass `hookName` in `clerkPlugin()` options + +```ts +fastify.register(clerkPlugin, { + hookName: 'preHandler', +}) +``` + ### `getAuth()` -The following example uses [`getAuth()`](/docs/references/nextjs/get-auth){{ target: '_blank' }} to retrieve the `userId`, which is used to protect the route and is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the current user's `User` object. +The `getAuth()` function retrieves the current user's authentication state from the request object. + +#### Example: Use `getAuth()` to retrieve the `userId` + +The following example demonstrates how to use `getAuth()` to protect a route and load user data. If the user is authenticated, their `userId` is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the user's information. If not authenticated, the request is rejected with a 403 status code. ```ts import 'dotenv/config' @@ -94,7 +95,10 @@ start() ## Configure `clerkPlugin()` for specific routes -If you want to use Clerk for specific pages only, you can register the plugin for specific routes. In the following example, the routes are split into protected and public routes. +To apply Clerk authentication only to specific routes, register the plugin in the scope of those routes. + +In the following example, the application is split into protected and public routes: + ```ts {{ filename: 'index.ts' }} import 'dotenv/config' From cecc2fe58a8143d9722f95262c856d4acb2422d2 Mon Sep 17 00:00:00 2001 From: vi Date: Mon, 13 Jan 2025 13:05:04 -0500 Subject: [PATCH 06/11] lint --- docs/references/fastify/overview.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index 016e91ab4b..2dea30c5e9 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -5,14 +5,12 @@ description: Learn how to integrate Clerk into your Fastify application using th The Clerk Fastify SDK is the recommended method for integrating Clerk into your Express application. Refer to the [quickstart guide](/docs/quickstarts/fastify) to get started. - ## Methods ### `clerkPlugin()` The `clerkPlugin()` is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid and if valid, attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. You can configure it to handle all routes or limit it to specific ones. - #### Example: Register `clerkPlugin()` ```ts @@ -32,7 +30,6 @@ The `clerkPlugin()` function accepts the [Backend API options](/docs/references/ You can also pass options to the plugin: - - `hookName` - `'onRequest' | 'preHandler'` @@ -99,7 +96,6 @@ To apply Clerk authentication only to specific routes, register the plugin in th In the following example, the application is split into protected and public routes: - ```ts {{ filename: 'index.ts' }} import 'dotenv/config' import Fastify, { FastifyPluginCallback } from 'fastify' From 24936586bc6a060036ee62989f8a5334568eb505 Mon Sep 17 00:00:00 2001 From: victoria Date: Tue, 14 Jan 2025 17:16:24 -0500 Subject: [PATCH 07/11] Apply suggestions from code review --- docs/references/fastify/overview.mdx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index 2dea30c5e9..6d6c9a9c33 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -9,7 +9,7 @@ The Clerk Fastify SDK is the recommended method for integrating Clerk into your ### `clerkPlugin()` -The `clerkPlugin()` is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid and if valid, attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. You can configure it to handle all routes or limit it to specific ones. +The `clerkPlugin()` is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid, it attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. You can configure it to handle all routes or limit it to specific ones. #### Example: Register `clerkPlugin()` @@ -26,9 +26,8 @@ fastify.register(clerkPlugin) ### Configure `clerkPlugin()` -The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) and the following additional options: +The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) in addition to the following: -You can also pass options to the plugin: - `hookName` @@ -51,7 +50,7 @@ The `getAuth()` function retrieves the current user's authentication state from #### Example: Use `getAuth()` to retrieve the `userId` -The following example demonstrates how to use `getAuth()` to protect a route and load user data. If the user is authenticated, their `userId` is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the user's information. If not authenticated, the request is rejected with a 403 status code. +The following example uses `getAuth()` to protect a route and load user data. If the user is authenticated, their `userId` is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the user's information. If not authenticated, the request is rejected with a 403 status code. ```ts import 'dotenv/config' From 0e905b105f8c3f316f0f291aae51963127caae4c Mon Sep 17 00:00:00 2001 From: Lennart Date: Wed, 15 Jan 2025 14:27:25 +0100 Subject: [PATCH 08/11] Update docs/quickstarts/fastify.mdx Co-authored-by: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com> --- docs/quickstarts/fastify.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/quickstarts/fastify.mdx b/docs/quickstarts/fastify.mdx index c7f65e061a..2dcd4f42fa 100644 --- a/docs/quickstarts/fastify.mdx +++ b/docs/quickstarts/fastify.mdx @@ -82,7 +82,7 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic The `clerkPlugin` is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin` to handle all routes or limit it to specific ones. - The following example registers the plugin for all routes. To register the plugin for specific routes only, refer to the [**Using Clerk for specific pages only**](/docs/references/fastify/overview#configure-clerk-plugin-for-specific-routes){{ target: '_blank' }} section. + The following example registers the plugin for all routes. To register the plugin for specific routes only, refer to the [**Using Clerk for specific pages only**](/docs/references/fastify/overview#configure-clerk-plugin-for-specific-routes) section. > [!IMPORTANT] > The `dotenv/config` module must be imported before any Clerk modules. This order is important because Clerk instances are created during the import process and rely on environment variables, such as API keys, to be initialized correctly. For more information, refer to the [Fastify docs](https://fastify.dev/docs/latest/Guides/Getting-Started/#loading-order-of-your-plugins). From dc1f797ffac116a8171de5a9e2dc18461ab66777 Mon Sep 17 00:00:00 2001 From: LekoArts Date: Wed, 15 Jan 2025 14:33:15 +0100 Subject: [PATCH 09/11] support dark mode for fastify icon --- docs/index.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.mdx b/docs/index.mdx index 119809eee6..c3122ca3af 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -115,7 +115,7 @@ Find all the guides and resources you need to develop with Clerk. - [Fastify](/docs/quickstarts/fastify) - Quickly add authentication and user management to your Fastify application. - - {} + - {} ## Explore by feature From c491040f1854c2b4dfc6a49951892756ac3a9c7a Mon Sep 17 00:00:00 2001 From: LekoArts Date: Wed, 15 Jan 2025 14:33:36 +0100 Subject: [PATCH 10/11] linting --- docs/references/fastify/overview.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index 6d6c9a9c33..ebe19a1a8c 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -28,7 +28,6 @@ fastify.register(clerkPlugin) The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) in addition to the following: - - `hookName` - `'onRequest' | 'preHandler'` From 13fd92798b869b9940c58c076660e917ee0a0b96 Mon Sep 17 00:00:00 2001 From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com> Date: Wed, 15 Jan 2025 15:05:02 -0500 Subject: [PATCH 11/11] docs review --- docs/_partials/clerk-options.mdx | 83 ++++++++++++++++ docs/_partials/fastify/get-auth.mdx | 48 ++++++++++ .../handling/js-backend-sdks.mdx | 89 ------------------ docs/quickstarts/fastify.mdx | 49 ++-------- docs/references/backend/overview.mdx | 84 +---------------- docs/references/fastify/overview.mdx | 94 +++++++------------ 6 files changed, 174 insertions(+), 273 deletions(-) create mode 100644 docs/_partials/clerk-options.mdx create mode 100644 docs/_partials/fastify/get-auth.mdx delete mode 100644 docs/backend-requests/handling/js-backend-sdks.mdx diff --git a/docs/_partials/clerk-options.mdx b/docs/_partials/clerk-options.mdx new file mode 100644 index 0000000000..e105bfc724 --- /dev/null +++ b/docs/_partials/clerk-options.mdx @@ -0,0 +1,83 @@ + + - `secretKey` (required) + - `string` + + The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + + --- + + - `jwtKey?` + - `string` + + The PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. For more information, refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). + + --- + + - `publishableKey?` + - `string` + + The Clerk Publishable Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + + --- + + - `domain?` + - `string` + + The domain of a [satellite application](/docs/advanced-usage/satellite-domains) in a multi-domain setup. + + --- + + - `isSatellite?` + - `boolean` + + Whether the instance is a satellite domain in a multi-domain setup. Defaults to `false`. + + --- + + - `proxyUrl?` + - `string` + + The proxy URL from a multi-domain setup. + + --- + + - `sdkMetadata?` + - `{ name: string, version: string }` + + Metadata about the SDK. + + --- + + - `telemetry?` + - `{ disabled: boolean, debug: boolean }` + + [Telemetry](/docs/telemetry) configuration. + + --- + + - `userAgent?` + - `string` + + The User-Agent request header passed to the Clerk API. + + --- + + - `apiUrl?` + - `string` + + The [Clerk Backend API](/docs/reference/backend-api){{ target: '_blank' }} endpoint. Defaults to `'https://api.clerk.com'`. + + --- + + - `apiVersion?` + - `string` + + The version passed to the Clerk API. Defaults to `'v1'`. + + --- + + - `audience?` + - `string | string[]` + + A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). + diff --git a/docs/_partials/fastify/get-auth.mdx b/docs/_partials/fastify/get-auth.mdx new file mode 100644 index 0000000000..0cdb58b848 --- /dev/null +++ b/docs/_partials/fastify/get-auth.mdx @@ -0,0 +1,48 @@ +The following example uses `getAuth()` to protect a route and load the user's data. If the user is authenticated, their `userId` is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to get the current user's [`User`](/docs/references/javascript/user/user){{ target: '_blank' }} object. If not authenticated, the request is rejected with a `403` status code. + +```ts +// dotenv must be imported before @clerk/fastify +import 'dotenv/config' +import Fastify from 'fastify' +import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' + +const fastify = Fastify({ logger: true }) + +fastify.register(clerkPlugin) + +// Use `getAuth()` to protect this route +fastify.get('/protected', async (request, reply) => { + try { + // Use `getAuth()` to get the user's ID + const { userId } = getAuth(request) + + // If user isn't authenticated, return a 403 error + if (!userId) { + return reply.code(403).send({ error: 'Unauthorized request' }) + } + + // Use `clerkClient` to access Clerk's Backend SDK methods + // and get the user's User object + const user = userId ? await clerkClient.users.getUser(userId) : null + + return reply.send({ + message: 'User retrieved successfully', + user, + }) + } catch (error) { + fastify.log.error(error) + return reply.code(500).send({ error: 'Failed to retrieve user' }) + } +}) + +const start = async () => { + try { + await fastify.listen({ port: 8080 }) + } catch (error) { + fastify.log.error(error) + process.exit(1) + } +} + +start() +``` diff --git a/docs/backend-requests/handling/js-backend-sdks.mdx b/docs/backend-requests/handling/js-backend-sdks.mdx deleted file mode 100644 index 4dee29e62b..0000000000 --- a/docs/backend-requests/handling/js-backend-sdks.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Handling requests with a JS Backend SDK -description: Learn how to handle authenticated requests with one of Clerk's JS Backend SDKs. ---- - -To handle authenticated requests, use one of the following JS Backend SDKs. - -## Clerk Express SDK - -The `clerkMiddleware()` function checks the request's cookies and headers for a session JWT. If the user has a valid session, the `clerkMiddleware()` function attaches the [properties](/docs/references/backend/types/auth-object#auth-object-properties) of the authenticated user to the request object. - -```js -import { clerkMiddleware } from '@clerk/express' - -const app = express() - -// Pass no parameters -app.use(clerkMiddleware()) - -// Pass options -app.use(clerkMiddleware(options)) -``` - -For more information on the Middleware functions and SDK features, see the [Express SDK](/docs/references/express/overview) page. - -## Clerk Fastify SDK - -The `clerkPlugin` checks the request's cookies and headers for a session JWT. If the user has a valid session, the `clerkPlugin` attaches the [properties](/docs/references/backend/types/auth-object#auth-object-properties) of the authenticated user to the request object. - -```ts -import 'dotenv/config' -import Fastify from 'fastify' -import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' - -const fastify = Fastify({ logger: true }) - -fastify.register(clerkPlugin) - -fastify.get('/', async (request, reply) => { - const { userId } = getAuth(request) - - // Protect the route from unauthenticated users - if (!userId) { - return reply.code(403).send({ error: 'Unauthorized request.' }) - } - - const user = userId ? await clerkClient.users.getUser(userId) : null - - return reply.send({ - message: 'User retrieved successfully.', - user, - }) -}) - -const start = async () => { - try { - await fastify.listen({ port: 8080 }) - } catch (error) { - fastify.log.error(error) - process.exit(1) - } -} - -start() -``` - -For more information on the Clerk plugin and SDK features, see the [Fastify SDK](/docs/quickstarts/fastify) page. - -## Clerk Backend SDK - -If you're not using Express or Fastify, use the `@clerk/backend` package to access `clerkClient`. - -```ts -import { createClerkClient } from '@clerk/backend' - -const clerkClient = createClerkClient({ - secretKey: process.env.CLERK_SECRET_KEY, - publishableKey: process.env.CLERK_PUBLISHABLE_KEY, -}) - -const { isSignedIn } = await clerkClient.authenticateRequest(req, { - jwtKey: process.env.CLERK_JWT_KEY, - authorizedParties: ['https://example.com'], -}) - -if (!isSignedIn) { - return Response.json({ status: 401 }) -} -``` diff --git a/docs/quickstarts/fastify.mdx b/docs/quickstarts/fastify.mdx index 2dcd4f42fa..409f76b097 100644 --- a/docs/quickstarts/fastify.mdx +++ b/docs/quickstarts/fastify.mdx @@ -43,7 +43,7 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic [Clerk's Fastify SDK](https://github.com/clerk/javascript/tree/main/packages/fastify) provides a range of backend utilities to simplify user authentication and management in your application. - To get started using Clerk with Fastify, add the SDK to your project: + Run the following command to install the SDK: ```bash {{ filename: 'terminal' }} @@ -78,11 +78,11 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic CLERK_SECRET_KEY={{secret}} ``` - ## Configure `clerkPlugin` for all routes + ## Configure `clerkPlugin()` for all routes - The `clerkPlugin` is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin` to handle all routes or limit it to specific ones. + The `clerkPlugin()` function is a Fastify plugin provided by Clerk to integrate authentication into your Fastify application. To ensure that Clerk's authentication and user management features are applied across your Fastify application, configure the `clerkPlugin()` to handle all routes or limit it to specific ones. - The following example registers the plugin for all routes. To register the plugin for specific routes only, refer to the [**Using Clerk for specific pages only**](/docs/references/fastify/overview#configure-clerk-plugin-for-specific-routes) section. + The following example registers the plugin for all routes. To register the plugin for specific routes, see the [reference docs](/docs/references/fastify/overview#configure-clerk-plugin-for-specific-routes). > [!IMPORTANT] > The `dotenv/config` module must be imported before any Clerk modules. This order is important because Clerk instances are created during the import process and rely on environment variables, such as API keys, to be initialized correctly. For more information, refer to the [Fastify docs](https://fastify.dev/docs/latest/Guides/Getting-Started/#loading-order-of-your-plugins). @@ -108,44 +108,9 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic start() ``` - ## Use `getAuth()` to access the auth state and protect routes + ## Protect your routes using `getAuth()` - The following example uses [`getAuth()`](/docs/references/nextjs/get-auth){{ target: '_blank' }} to retrieve the `userId`, which is used to protect the route and is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the current user's `User` object. + The [`getAuth()`](/docs/references/fastify/overview#get-auth) helper retrieves the current user's authentication state from the `request` object. It returns the [`Auth` object](/docs/references/backend/types/auth-object#auth-object){{ target: '_blank' }}. - ```ts {{ filename: 'index.ts' }} - import 'dotenv/config' - import Fastify from 'fastify' - import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' - - const fastify = Fastify({ logger: true }) - - fastify.register(clerkPlugin) - - fastify.get('/', async (request, reply) => { - const { userId } = getAuth(request) - - // Protect the route from unauthenticated users - if (!userId) { - return reply.code(403).send({ error: 'Unauthorized request.' }) - } - - const user = userId ? await clerkClient.users.getUser(userId) : null - - return reply.send({ - message: 'User retrieved successfully.', - user, - }) - }) - - const start = async () => { - try { - await fastify.listen({ port: 8080 }) - } catch (error) { - fastify.log.error(error) - process.exit(1) - } - } - - start() - ``` + diff --git a/docs/references/backend/overview.mdx b/docs/references/backend/overview.mdx index e186be41e6..88b1b2bc9c 100644 --- a/docs/references/backend/overview.mdx +++ b/docs/references/backend/overview.mdx @@ -285,89 +285,7 @@ The `createClerkClient()` function requires an `options` object. It is recommend The following options are available: - - - `secretKey` (required) - - `string` - - The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. - - --- - - - `jwtKey?` - - `string` - - The PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. For more information, refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). - - --- - - - `publishableKey?` - - `string` - - The Clerk Publishable Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. - - --- - - - `domain?` - - `string` - - The domain of a [satellite application](/docs/advanced-usage/satellite-domains) in a multi-domain setup. - - --- - - - `isSatellite?` - - `boolean` - - Whether the instance is a satellite domain in a multi-domain setup. Defaults to `false`. - - --- - - - `proxyUrl?` - - `string` - - The proxy URL from a multi-domain setup. - - --- - - - `sdkMetadata?` - - `{ name: string, version: string }` - - Metadata about the SDK. - - --- - - - `telemetry?` - - `{ disabled: boolean, debug: boolean }` - - [Telemetry](/docs/telemetry) configuration. - - --- - - - `userAgent?` - - `string` - - The User-Agent request header passed to the Clerk API. - - --- - - - `apiUrl?` - - `string` - - The [Clerk Backend API](/docs/reference/backend-api){{ target: '_blank' }} endpoint. Defaults to `'https://api.clerk.com'`. - - --- - - - `apiVersion?` - - `string` - - The version passed to the Clerk API. Defaults to `'v1'`. - - --- - - - `audience?` - - `string | string[]` - - A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). - + ## Get the `userId` and other properties diff --git a/docs/references/fastify/overview.mdx b/docs/references/fastify/overview.mdx index ebe19a1a8c..2992be8558 100644 --- a/docs/references/fastify/overview.mdx +++ b/docs/references/fastify/overview.mdx @@ -5,13 +5,13 @@ description: Learn how to integrate Clerk into your Fastify application using th The Clerk Fastify SDK is the recommended method for integrating Clerk into your Express application. Refer to the [quickstart guide](/docs/quickstarts/fastify) to get started. -## Methods +## `clerkPlugin()` -### `clerkPlugin()` +The `clerkPlugin()` function is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid, it attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object){{ target: '_blank' }} object to the `request` object under the `auth` key. -The `clerkPlugin()` is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid, it attaches the [`Auth`](/docs/references/backend/types/auth-object#auth-object) object to the request object under the `auth` key. You can configure it to handle all routes or limit it to specific ones. +You can register the plugin for [all routes](#example-register-clerk-plugin-for-all-routes) or [limit it to specific ones](#example-register-clerk-plugin-for-specific-routes). -#### Example: Register `clerkPlugin()` +### Example: Register `clerkPlugin()` for all routes ```ts // dotenv must be imported before @clerk/fastify @@ -22,59 +22,6 @@ import { clerkPlugin } from '@clerk/fastify' const fastify = Fastify({ logger: true }) fastify.register(clerkPlugin) -``` - -### Configure `clerkPlugin()` - -The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) in addition to the following: - - - - `hookName` - - `'onRequest' | 'preHandler'` - - Determines which of Fastify's [Request/Reply hooks](https://fastify.dev/docs/latest/Reference/Hooks/#requestreply-hooks) Clerk should run. Default: `'preHandler'` - - -#### Example: Pass `hookName` in `clerkPlugin()` options - -```ts -fastify.register(clerkPlugin, { - hookName: 'preHandler', -}) -``` - -### `getAuth()` - -The `getAuth()` function retrieves the current user's authentication state from the request object. - -#### Example: Use `getAuth()` to retrieve the `userId` - -The following example uses `getAuth()` to protect a route and load user data. If the user is authenticated, their `userId` is passed to [`clerkClient.users.getUser()`](/docs/references/backend/user/get-user){{ target: '_blank' }} to retrieve the user's information. If not authenticated, the request is rejected with a 403 status code. - -```ts -import 'dotenv/config' -import Fastify from 'fastify' -import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' - -const fastify = Fastify({ logger: true }) - -fastify.register(clerkPlugin) - -fastify.get('/', async (request, reply) => { - const { userId } = getAuth(request) - - // Protect the route from unauthenticated users - if (!userId) { - return reply.code(403).send({ error: 'Unauthorized request.' }) - } - - const user = userId ? await clerkClient.users.getUser(userId) : null - - return reply.send({ - message: 'User retrieved successfully.', - user, - }) -}) const start = async () => { try { @@ -88,13 +35,13 @@ const start = async () => { start() ``` -## Configure `clerkPlugin()` for specific routes +### Example: Register `clerkPlugin()` for specific routes To apply Clerk authentication only to specific routes, register the plugin in the scope of those routes. In the following example, the application is split into protected and public routes: -```ts {{ filename: 'index.ts' }} +```ts {{ filename: 'index.ts', collapsible: true }} import 'dotenv/config' import Fastify, { FastifyPluginCallback } from 'fastify' import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify' @@ -143,3 +90,32 @@ const start = async () => { start() ``` + +### `clerkPlugin()` options + +The `clerkPlugin()` function accepts the following options: + + + + + - `hookName` + - `'onRequest' | 'preHandler'` + + Determines which of Fastify's [Request/Reply hooks](https://fastify.dev/docs/latest/Reference/Hooks/#requestreply-hooks) Clerk should run. Default: `'preHandler'` + + +#### Example: Pass `hookName` in `clerkPlugin()` options + +```ts +fastify.register(clerkPlugin, { + hookName: 'preHandler', +}) +``` + +## `getAuth()` + +The `getAuth()` helper retrieves the current user's authentication state from the `request` object. It returns the [`Auth` object](/docs/references/backend/types/auth-object#auth-object){{ target: '_blank' }}. See the [Next.js reference documentation](/docs/references/nextjs/get-auth){{ target: '_blank' }} for more examples on how to use the returned `Auth` object. + +### Example: Use `getAuth()` to retrieve the `userId` + +