Search code examples
javascriptreactjsnext.jsnext-auth

I can't get session of next-auth.js in _app.js


I have two provider but I can't use two of them at the same time when i try to log user using useSession there's an existencetime but not a user(empty object returns) I have backend that returns the user data

_app.js

const MyApp = ({ Component, session, ...rest }) => {
  const router = useRouter();
  const { store, props } = wrapper.useWrappedStore(rest);
  return (
    <Provider store={store}>
      <SessionProvider session={session}>
        <Component {...props.pageProps} key={router.asPath} />
      </SessionProvider>
    </Provider>
  );
};

export default MyApp;

Login handler in the login page

const loginHandler = async (e) => {
    e.preventDefault();

    const result = await signIn("credentials", {
      username: loginValues.username,
      password: loginValues.password,
      redirect: false,
    });
  };

[...nextauth].js

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: {
          label: "username",
          type: "text",
        },
        password: {
          label: "password",
          type: "password",
        },
      },
      async authorize(credentials, req) {
        const { username, password } = credentials;
        const res = await fetch("http://localhost:8080/login", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            username,
            password,
          }),
        });
        const user = await res.json();

        return user;
      },
    }),
  ],
  session: {
    strategy: "jwt",
  },
  pages: {
    signIn: "/login",
  },
};

export default NextAuth(authOptions);

Solution

  • Here you are not updating the session you are just returning the user from the response so you have to use callbacks to achieve that.

    JWT callback
    This callback is called whenever a JSON Web Token is created (i.e. at sign in) or updated (i.e whenever a session is accessed in the client). The returned value will be encrypted, and it is stored in a cookie.

    Session callback
    The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token (like access_token and user.id from above) via the jwt() callback, you have to explicitly forward it here to make it available to the client.

     callbacks: {
        async jwt({ user, token }) {
          //   update token if user is returned
          if (user) {
            token.user = user;
          }
          //   return final_token
          return token;
        },
        async session({ session, token, user }) {
          //  update session from token
          session.user = token.user; // you can add the properties you want instead of overwriting the session.user
          return session;
        },
      },