Published on

Hono + Next.js + Clerk

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Use Clerk with Hono middleware

  1. Install Packages

    pnpm install hono @hono/clerk-auth @clerk/backend
    
  2. Set environment variables or share Next config

    // .env.local
    NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
    CLERK_SECRET_KEY=
    
  3. 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,
      })
    );
    
  4. 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" });
    });
    ...