エラーが発生した状況
middleware.ts
に以下のように記述し、リダイレクトするようにしていました。
middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export const config = {
matcher: ['/((?!icons|logos|_next/static|favicon.ico|manifest.json).*)'],
}
export async function middleware(req: NextRequest) {
const hasAuthCookie = req.cookies.has('auth_cookie')
if (!hasAuthCookie) {
const loginUrl = new URL('/login', req.url)
return NextResponse.redirect(loginUrl)
}
// ...
}
サーバーアクションを使用した際にミドルウェアでリダイレクトすると以下のようなエラーが発生しました。
failed to forward action response TypeError: fetch failed
at node:internal/deps/undici/undici:13185:13
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async rC (/home/node/project/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:15:4216)
at async rE (/home/node/project/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:15:8094)
at async r7 (/home/node/project/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:18:1144)
at async doRender (/home/node/project/node_modules/next/dist/server/base-server.js:1413:30)
at async cacheEntry.responseCache.get.routeKind (/home/node/project/node_modules/next/dist/server/base-server.js:1574:28)
at async NextNodeServer.renderToResponseWithComponentsImpl (/home/node/project/node_modules/next/dist/server/base-server.js:1482:28)
at async NextNodeServer.renderPageComponent (/home/node/project/node_modules/next/dist/server/base-server.js:1908:24)
at async NextNodeServer.renderToResponseImpl (/home/node/project/node_modules/next/dist/server/base-server.js:1946:32) {
[cause]: Error
at makeNetworkError (node:internal/deps/undici/undici:8968:35)
at httpRedirectFetch (node:internal/deps/undici/undici:10515:32)
at httpFetch (node:internal/deps/undici/undici:10475:28)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async node:internal/deps/undici/undici:10212:20
at async mainFetch (node:internal/deps/undici/undici:10202:20)
}
回避方法
middleware.ts
のconfig
を以下のように変更してサーバーアクションの場合は実行されないようにすることでエラーを回避できます。
middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export const config = {
- matcher: ['/((?!icons|logos|_next/static|favicon.ico|manifest.json).*)'],
+ matcher: [
+ {
+ source: '/((?!icons|logos|_next/static|favicon.ico|manifest.json).*)',
+ missing: [
+ { type: 'header', key: 'next-action' },
+ ],
+ },
+ ],
}
export async function middleware(req: NextRequest) {
const hasAuthCookie = req.cookies.has('auth_cookie')
if (!hasAuthCookie) {
const loginUrl = new URL('/login', req.url)
return NextResponse.redirect(loginUrl)
}
// ...
}
参考