Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Fastify reference docs #1869

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions docs/_partials/clerk-options.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<Properties>
- `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).
</Properties>
48 changes: 48 additions & 0 deletions docs/_partials/fastify/get-auth.mdx
Original file line number Diff line number Diff line change
@@ -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()
```
89 changes: 0 additions & 89 deletions docs/backend-requests/handling/js-backend-sdks.mdx

This file was deleted.

6 changes: 6 additions & 0 deletions docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ Find all the guides and resources you need to develop with Clerk.
- [Ruby on Rails](/docs/references/ruby/overview)
- Integrate user management and authentication into your Ruby application.
- {<svg viewBox="0 0 32 32" fill="none"><path fill="#CC342D" d="M25.164 2.611c3.407.59 4.374 2.92 4.302 5.36l.017-.035-1.534 20.098L8.012 29.4h.018c-1.655-.07-5.344-.221-5.512-5.378l1.848-3.371 3.167 7.4.565 1.317 3.152-10.274-.034.008.018-.034 10.399 3.321-1.569-6.102-1.112-4.382 9.91-.639-.692-.573-7.114-5.8L25.167 2.6l-.003.011ZM8.28 8.218c4.001-3.97 9.165-6.316 11.148-4.315 1.98 1.997-.118 6.86-4.127 10.827-4.003 3.968-9.104 6.442-11.082 4.446-1.984-1.997.05-6.985 4.058-10.955l.003-.003Z"/></svg>}

---

- [Fastify](/docs/quickstarts/fastify)
LekoArts marked this conversation as resolved.
Show resolved Hide resolved
- Quickly add authentication and user management to your Fastify application.
- {<svg viewBox="0 0 32 32"><path style={{ fill: 'var(--light, black) var(--dark, white)' }} d="M30.056 8.841 31 6.298l-.04-.157L21.617 8.7c.994-1.498.653-2.7.653-2.7s-2.983 1.98-5.24 1.929c-2.256-.052-2.982-.678-6.442.469s-4.438 4.667-5.44 5.421C4.146 14.575 1 17.04 1 17.04l.007.044 2.836-.94s-.777.763-2.43 3.079l-.077-.074.002.016s1.329 2.111 2.633 1.72c.152-.049.3-.113.441-.19.525.303 1.21.602 1.967.685a12.63 12.63 0 0 1-.94-1.323l.354-.24-.055.042 1.08.412-.12-1.057.01-.007 1.06.404-.132-.96c.135-.073.27-.142.403-.207l1.109-4.35 4.575-3.245-.364.951c-.928 2.373-2.67 2.931-2.67 2.931l-.727.287c-.54.665-.768.828-.954 3.059.436-.114.852-.14 1.23-.037 1.955.548 2.632 2.998 2.106 3.675-.132.17-.446.46-.842.8h-.793l-.01.668-.082.066H9.81l-.01.652c-.071.057-.142.112-.213.166-.759.017-1.719-.67-1.719-.67 0 .624.501 1.589.501 1.589l.09-.045-.077.058s2.03 1.408 3.309.886c1.138-.461 4.08-2.872 6.621-4.014L26 19.764l1.014-2.73-5.859 1.604v-2.453l6.873-1.883 1.014-2.732-7.887 2.161v-2.452l8.9-2.438ZM16.103 14.04l1.824-.5.024.096-.57 1.533-1.89.518.612-1.647Zm.63 3.281-1.891.519.61-1.647 1.824-.5.024.096-.567 1.532Zm2.463-.55-1.89.518.61-1.647 1.825-.5.024.095-.569 1.533Z"/></svg>}
</Cards>

## Explore by feature
Expand Down
13 changes: 13 additions & 0 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2427,6 +2427,19 @@
]
]
},
{
"title": "Fastify",
"collapse": true,
"icon": "fastify",
"items": [
[
{
"title": "Overview",
"href": "/docs/references/fastify/overview"
}
]
]
},
{
"title": "React Router",
"collapse": true,
Expand Down
3 changes: 2 additions & 1 deletion docs/manifest.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@
"vue",
"x",
"expo",
"nuxt"
"nuxt",
"fastify"
]
}
}
Expand Down
103 changes: 7 additions & 96 deletions docs/quickstarts/fastify.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:

<CodeBlockTabs options={["npm", "yarn", "pnpm"]}>
```bash {{ filename: 'terminal' }}
Expand Down Expand Up @@ -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/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, 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).
Expand All @@ -108,98 +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()
```
<Include src="_partials/fastify/get-auth" />
</Steps>

## 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()
```
Loading
Loading