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 11 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
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" fill="none"><path fill="#000" 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
56 changes: 1 addition & 55 deletions docs/quickstarts/fastify.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
LekoArts marked this conversation as resolved.
Show resolved Hide resolved

> [!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 Down Expand Up @@ -149,57 +149,3 @@ Learn how to integrate Clerk into your Fastify backend for secure user authentic
start()
```
</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()
```
146 changes: 146 additions & 0 deletions docs/references/fastify/overview.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
---
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. 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, 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()`

```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)
```

### Configure `clerkPlugin()`

The `clerkPlugin()` function accepts the [Backend API options](/docs/references/backend/overview#options) in addition to the following:


<Properties>
- `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'`
</Properties>

#### 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 {
await fastify.listen({ port: 8080 })
} catch (error) {
fastify.log.error(error)
process.exit(1)
}
}

start()
```

## Configure `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' }}
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