2023-10-27 15:50:22 +08:00
|
|
|
# Clerk middleware for Hono
|
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
[](https://codecov.io/github/honojs/middleware)
|
|
|
|
|
2023-10-27 15:50:22 +08:00
|
|
|
This is a [Clerk](https://clerk.com) third-party middleware for [Hono](https://github.com/honojs/hono).
|
|
|
|
|
|
|
|
This middleware can be used to inject the active Clerk session into the request context.
|
|
|
|
|
|
|
|
## Installation
|
|
|
|
|
|
|
|
```plain
|
|
|
|
npm i hono @hono/clerk-auth @clerk/backend
|
|
|
|
```
|
|
|
|
|
|
|
|
## Configuration
|
|
|
|
|
|
|
|
Before starting using the middleware you must set the following environment variables:
|
|
|
|
|
|
|
|
```plain
|
|
|
|
CLERK_SECRET_KEY=<You-secret-key>
|
|
|
|
CLERK_PUBLISHABLE_KEY=<Your-publishable-key>
|
|
|
|
```
|
|
|
|
|
|
|
|
## How to Use
|
|
|
|
|
|
|
|
```ts
|
|
|
|
import { clerkMiddleware, getAuth } from '@hono/clerk-auth'
|
|
|
|
import { Hono } from 'hono'
|
|
|
|
|
|
|
|
const app = new Hono()
|
|
|
|
|
|
|
|
app.use('*', clerkMiddleware())
|
|
|
|
app.get('/', (c) => {
|
|
|
|
const auth = getAuth(c)
|
|
|
|
|
|
|
|
if (!auth?.userId) {
|
|
|
|
return c.json({
|
2025-03-19 16:53:11 +08:00
|
|
|
message: 'You are not logged in.',
|
2023-10-27 15:50:22 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.json({
|
|
|
|
message: 'You are logged in!',
|
2025-03-19 16:53:11 +08:00
|
|
|
userId: auth.userId,
|
2023-10-27 15:50:22 +08:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
export default app
|
|
|
|
```
|
|
|
|
|
|
|
|
## Accessing instance of Backend API client
|
|
|
|
|
|
|
|
```ts
|
|
|
|
import { clerkMiddleware, getAuth } from '@hono/clerk-auth'
|
|
|
|
import { Hono } from 'hono'
|
|
|
|
|
|
|
|
const app = new Hono()
|
|
|
|
|
|
|
|
app.use('*', clerkMiddleware())
|
|
|
|
app.get('/', async (c) => {
|
2023-11-03 02:41:00 +08:00
|
|
|
const clerkClient = c.get('clerk')
|
2023-10-27 15:50:22 +08:00
|
|
|
|
|
|
|
try {
|
|
|
|
const user = await clerkClient.users.getUser('user_id_....')
|
|
|
|
|
|
|
|
return c.json({
|
|
|
|
user,
|
|
|
|
})
|
|
|
|
} catch (e) {
|
2025-03-19 16:53:11 +08:00
|
|
|
return c.json(
|
|
|
|
{
|
|
|
|
message: 'User not found.',
|
|
|
|
},
|
|
|
|
404
|
|
|
|
)
|
2023-10-27 15:50:22 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
export default app
|
|
|
|
```
|
|
|
|
|
|
|
|
## Author
|
|
|
|
|
|
|
|
Vaggelis Yfantis <https://github.com/octoper>
|