📖

【Drizzle ORM】NextJs14 と Drizzle ORM【#12 Hono Clerk Middleware 】

2024/08/03に公開

【#12 Hono Clerk Middleware 】

YouTube: https://youtu.be/LWc-o30Z5Bw
https://youtu.be/LWc-o30Z5Bw

今回はClerkの基本的なミドルウェアの設定と、
Honoの個別のルートにClerkのミドルウェアの設定を行う方法について
解説していきます。

https://clerk.com/docs/references/nextjs/clerk-middleware

https://hono.dev/docs/middleware/third-party

https://github.com/honojs/middleware/tree/main/packages/clerk-auth

npm i @hono/clerk-auth

インストールができましたら、
.env.localのファイルで
「NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY」をコピーして
「CLERK_PUBLISHABLE_KEY」を設定します。

こちらは両方必要です。

.env.local
DATABASE_URL=postgresql://my........................

//キーは同じものを使用しています。
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_ZGVsaWNh.............
CLERK_PUBLISHABLE_KEY=pk_test_ZGVsaWNh.....................

CLERK_SECRET_KEY=sk_test_....................
WEBHOOK_SECRET=whsec_ZOA.........................

NEXT_PUBLIC_APP_URL=http://localhost:3000
middleware.ts
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";

const isProtectedRoute = createRouteMatcher(["/", "/api(.*)"]);

export default clerkMiddleware((auth, req) => {
  if (!isProtectedRoute(req)) auth().protect();
});

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
app/api/[[...route]]/users.ts
import { Hono } from "hono";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";

import { db } from "@/db/drizzle";
import { users } from "@/db/schema";
import { eq } from "drizzle-orm";

const app = new Hono()
  .get("/", async (c) => {
    const data = await db.select().from(users);

    return c.json({
      users: data,
    });
  })
  .get("/me", clerkMiddleware(), async (c) => {
    const auth = getAuth(c);

    if (!auth?.userId) {
      return c.json({ error: "Unauthorized" }, 401);
    }

    const [data] = await db
      .select()
      .from(users)
      .where(eq(users.clerkId, auth.userId));

    if (!data) {
      return c.json({ error: "User not found" }, 404);
    }

    return c.json({ user: data });
  })
  .get(
    "/:id",
    zValidator(
      "param",
      z.object({
        id: z.string(),
      })
    ),
    async (c) => {
      // const id = c.req.param("id");
      const { id } = c.req.valid("param");

      const [data] = await db.select().from(users).where(eq(users.id, id));

      if (!data) {
        return c.json({ error: "User not found" }, 404);
      }

      // if (data.length === 0) {
      //   return c.json({ error: "User not found" }, 404);
      // }

      return c.json({
        user: data,
      });
    }
  );

export default app;

Discussion