I recently updated from next-auth 4.19 to 4.22.1.
Before the update, my code worked fine.
I have an API route, and in that code, I have a simple:
export default async function handler(req, res) {
if (req.method === 'POST') {
//first, check if they're logged in.
console.log("test54646");
const session = await getSession({ req });
console.log("test789987977");
...
//return a JSON object.
Before, the update, the code worked to completion (it returned a JSON object).
After the update, I get an error:
test54646
[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
}
test789987977
It looks like getSession({req}) is giving the error?
Strangely, if I hit the URL directly in my browser: http://localhost:3000/api/auth/session
It works fine. My browser shows the JSON object that it's supposed to return.
I looked up the documentation for this error at: https://next-auth.js.org/errors
And it just says that I have to configure the NEXTAUTH_URL environment variable.
So I went into .env.local, and set: NEXTAUTH_URL=http://localhost:3000
And I still have the error.
Can anyone explain how to fix this? I really would like to upgrade to 4.22, because of the new update() and refresh() functionality:
https://github.com/nextauthjs/next-auth/discussions/3941
Thank you.
I found the solution:
turns out, if it's executing on the server, you use getServerSession(), but if you're on the client side, you use getSession(). I guess it worked fine using getSession() on the server side in 4.19, but in 4.22.1, it gives the error. The documentation says it's still OK to use getSession() on the server side, but it no longer works for me.
Source: https://next-auth.js.org/configuration/nextjs#unstable_getserversession
See section entitled "In API Routes"