ClerkをNextjsのApp Routerで使う時、middlewareの扱いに注意しよう
ドキュメントをよく読んで、ClerkをNext.jsのApp Routerで使う際の注意点をまとめました。ClerkMiddlewareをプロジェクトルートに配置し、Middlewareのmatcherも設定する必要があります。プロジェクトルートに配置してもうまく動かない場合は、ファイルをプロジェクトルートに移動させると問題が解決される可能性があります。参考記事に詳細が記載されています。
広告ここから
広告ここまで
目次
ドキュメントをよく読むとちゃんと書かれているのですが、App Routerやmiddlewareに慣れていないとハマりそうだったので、覚書としてまとめました。
まず結論
ClerkをNextjsのApp Routerで使う時は、middlewareファイルをapp
ディレクトリ内に置かないようにする。正解は、プロジェクトルートに配置すること。
うまく動かなかったコード
はじめ、app/middleware.ts
を作成して以下のコードを追加しました。
import { clerkMiddleware } from "@clerk/nextjs/server";
export default clerkMiddleware();
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
};
これを実行しようとすると、エラーが発生します。
✘ [ERROR] Error: Clerk: auth() was called but Clerk can't detect usage of clerkMiddleware(). Please ensure the following:
- clerkMiddleware() is used in your Next.js Middleware.
- Your Middleware matcher is configured to match this route or page.
- If you are using the src directory, make sure the Middleware file is inside of it.
For more details, see https://clerk.com/docs/quickstarts/nextjs
対処法: プロジェクトルートにファイルを移動する
対処法はこれだけです。mv
コマンドで移動させれば、動くようになります。
mv app/middleware.ts ./