nextjs app routerのmiddlewareのmatcherで全てのpathを対象にする
TL;DR
方法は2つパターン。
- configをなくす
- matcherで記載する
背景
nextjs exampleを確認している際に、ふと気になった。
0. middleware
(src/)middleware.ts
import { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
console.log(request.url)
}
export const config = {
matcher: "/api/:path*"
}
1. config を削除する
(src/)middleware.ts
import { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
console.log(request.url)
}
next_web_container | http://localhost:3000/
next_web_container | GET / 200 in 39ms
next_web_container | http://localhost:3000/_next/static/css/app/layout.css?v=1730426140917
next_web_container | http://localhost:3000/_next/static/chunks/webpack.js?v=1730426140917
next_web_container | http://localhost:3000/_next/static/chunks/main-app.js?v=1730426140917
next_web_container | http://localhost:3000/_next/static/chunks/app-pages-internals.js
next_web_container | http://localhost:3000/_next/static/chunks/app/page.js
next_web_container | http://localhost:3000/favicon.ico
next_web_container | GET /favicon.ico 200 in 11ms
2. matcherで記載する
(src/)middleware.ts
import { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
console.log(request.url)
}
export const config = {
matcher: ['/:path*'],
}
next_web_container | http://localhost:3000/
next_web_container | GET / 200 in 21ms
next_web_container | http://localhost:3000/_next/static/css/app/layout.css?v=1730426250311
next_web_container | http://localhost:3000/_next/static/chunks/webpack.js?v=1730426250311
next_web_container | http://localhost:3000/_next/static/chunks/app/page.js
next_web_container | http://localhost:3000/_next/static/chunks/main-app.js?v=1730426250311
next_web_container | http://localhost:3000/_next/static/chunks/app-pages-internals.js
next_web_container | http://localhost:3000/favicon.ico
next_web_container | GET /favicon.ico 200 in 14ms