2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NextJS middlewareでError: The edge runtime does not support Node.js '...' module. などというエラーが出る場合

Posted at

Screenshot 2023-03-27 at 12.10.02.png

ここを見ろと言われる

However, the Edge Runtime does not support Node.js APIs and globals.

以下のこれらは駄目 (unsupported-apis)

middleware内で大きめなnpmなどを使っていると(firebaseとか)、だいたい引っかかる。

解決方法

https://nextjs.org/docs/api-reference/edge-runtime にはfetchは使えると書いてある。

Screenshot 2023-03-27 at 12.14.02.png

なので/pages/api/...にmiddleware内で処理したい内容を書いて、そこをfetchしてしまえばいい。

middleware.ts
export async function middleware(request: NextRequest) {
  const redirect404 = NextResponse.redirect(new URL("/404", request.url))

  const value = request.cookies.get("login.user.cookie.name")?.value
  if (!value) {
    // クッキーがないなら404とか
    return redirect404
  }

  if (!(await fetch(new URL(`/api/user/cookie/check/${value}`, request.url))).ok) {
    // クッキーのデータからユーザーが見つからないなら404とか
    return redirect404
  }

  const response = NextResponse.next()

  // クッキーを更新するとか
  response.cookies.set("login.user.cookie.name", value, {
    httpOnly: true,
    path: "/",
    sameSite: "strict",
    secure: true,
    expires: ...
  })

  return response
}

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?