nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.58k stars 3.46k forks source link

[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 } #7339

Closed BADHON512 closed 1 year ago

BADHON512 commented 1 year ago

Environment

const isAuthenticatedUser = async (req, res, next) => { const session = await getSession({req} );

if (!session) { return next(new Error("Login first to access this route", 401)); }

req.user = session.user; console.log( req.user = session.user); next(); };

export { isAuthenticatedUser };

Reproduction URL

..

Describe the issue

import ConnectDB from '@/backend/config/connectdb'; import bcrypt from 'bcryptjs'; import NextAuth from 'next-auth/next'; import CredentialProvider from "next-auth/providers/credentials" import User from './../../../backend/config/Model/user';

export default async function auth(req, res) { return NextAuth(req, res, { session: { strategy: "jwt" }, providers: [ CredentialProvider({ async authorize(credentials, req) { ConnectDB() const { email, password } = credentials const user = await User.findOne({ email }) if (!user) { throw new Error("invalid email") } const matchedPassword = bcrypt.compare(password, user.password) if (!matchedPassword) { throw new Error("invalid password") } return user

            }
        })
    ], callbacks: {
        jwt: async ({ token, user }) => {
            user && (token.user = user);

            return token;
        },
        session: async ({ session, token }) => {
            session.user = token.user;

            // delete password from session
            //delete session?.user?.password;

            return session;
        },
    },
     secret:process.env.NEXTAUTH_SECRET
})

}

How to reproduce

export const PostTask=async(data)=>{ try {

const response= await axios.post(${process.env.NEXTAUTH_URL}/api/todo,data) console.log(process.env.API_URL,"badhon"); return response?.data } catch (error) { console.log(error.message); } }

Expected behavior

i am login but when i post data show that "Login first to access this route

handel.use(isAuthenticatedUser).post(PostTodo) handel.use(isAuthenticatedUser).get(getTodo)

jimapl commented 1 year ago

I also suddenly am having this issue!

jimapl commented 1 year ago

bump! My production app broke, no code changes whatsoever.

jimapl commented 1 year ago

So after a npm i on my production server all hell broke loose. However I managed to solve it by replacing all my: await getSession({req}) with await getServerSession(req, res, returnAuthOptions(req,res))

Where returnAuthOptions is an export in my [...nextauth] api route which returns the nextauth config obj.

Very poor documentation btw Nextauth team!