💭

Next.jsのAPI RoutesでgetSessionを使うとnullがかえってくる

2023/04/11に公開

Next.jsのAPI RoutesでPOST時にNextAuth.jsのgetSessionを使うとnullがかえってきてしまう

page/api/index.ts
import { NextApiRequest, NextApiResponse } from "next"
import { getSession } from 'next-auth/react'

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
  const session = await getSession({ req })
  // ・・・
}
error
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error undefined {
error: {},
url: 'http://localhost:3000/api/auth/session',
message: undefined
}

getSessiongetServerSessionに書き換える

page/api/index.ts
import { NextApiRequest, NextApiResponse } from "next"
import { authOptions } from './auth/[...nextauth]'
import { getServerSession } from 'next-auth/next'

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
  const session = await getServerSession(req, res, authOptions)
  // ・・・
}

ちゃんとかえってきます

参考

https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes

Discussion