- Published on
Hono + Next.js + Clerk
- Authors
- Name
- Shelton Ma
Use Clerk with Hono middleware
Install Packages
pnpm install hono @hono/clerk-auth @clerk/backend
Set environment variables or share Next config
// .env.local NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= CLERK_SECRET_KEY=
Enable middleware in hono
// src/app/api/[[...route]]/route.ts import { clerkMiddleware, getAuth } from '@hono/clerk-auth' // app.use('*', clerkMiddleware()) app.use( "*", clerkMiddleware({ secretKey: process.env.CLERK_SECRET_KEY, publishableKey: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, }) );
Use getAuth
// src/app/api/[[...route]]/hello.ts ... const app = new Hono().get("/", (c) => { const auth = getAuth(c) if (!auth?.userId) { return c.json({ message: 'Unauthorized', }, 401) } return c.json({ message: "Hello World" }); }); ...