NextAuthのCredentials providerでリクエストヘッダーが消えてしまう。

imatomix
2021年11月5日 6:26

環境

  • Node: v16.x
  • Next.js: v12
  • NextAuth: v3.x
  • credentials で id & パスワード 認証をしている

エラー内容

Nodeのバージョンを14.xから16.xに上げたらNextAuthの認証部分でエラーが起きた。

[next-auth][error][client_fetch_error]
https://next-auth.js.org/errors#client_fetch_error session TypeError: Cannot read properties of undefined

しかし探ってみると、原因は上記エラー内容とは違っていて、 Credenrialsプロバイダの authorize メソッドに渡していた req オブジェクトから、以前はとれてたはずの headers 情報が抜け落ちていたからだった。

具体的にはここ。
/pages/auth/[...nextauth.ts]
import { NextApiRequest, NextApiResponse } from 'next' import NextAuth from 'next-auth' const options: NextAuthOptions = { providers: [ Providers.Credentials({ authorize: (credentials: AuthProps, req) => { console.log(req.header) // undefined になる // 中略 } }) ] } export default ( req: NextApiRequest, res: NextApiResponse ): void => NextAuth(req, res, options)

対応

しょうがないので、 options を外だしせずに、(req, res) => NextAuth() 内に入れてreqを直接受け取ることにしたらうまくいった。

/pages/auth/[...nextauth.ts]
import { NextApiRequest, NextApiResponse } from 'next' import NextAuth from 'next-auth' export default ( req: NextApiRequest, res: NextApiResponse ): void => NextAuth(req, res, { providers: [ Providers.Credentials({ authorize: (credentials: AuthProps) => { console.log(req.header) // 無事に表示される // 中略 } }) ] }

恐らく、そのうちNextAuthが対応するんだろうと思うけど、それ以上に、v4でいろいろ変わりそう。