Use Clerk with Hono middleware

Category
Community
Published

Hono is a great minimal web framework for building applications across any edge runtime and now with Hono's middleware and our community SDK, you can secure it with Clerk.

Install the middleware

To install the Clerk middleware for Hono, follow the instructions provided to set up and configure the middleware in Hono.

npm i hono @hono/clerk-auth @clerk/backend

Configure the middleware

Before you start using the Clerk middleware, you'll need to set the following environment variables:

CLERK_SECRET_KEY=<your-secret-key>
CLERK_PUBLISHABLE_KEY=<your-publishable-key>

Use the middleware

Here is a quick example on how to use the Clerk middleware for Hono:

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({
      message: 'You are not logged in.',
    })
  }

  return c.json({
    message: 'You are logged in!',
    userId: auth.userId,
  })
})

export default app

And that's it. Your app is now secured and running on the edge. Find more about Clerk's Hono middleware on GitHub.