網站搜尋

typescript - 為什麼我在 Nextjs 成功登入時,session 卻是 null?


我使用的是 Nextjs 14、NextAuth ^4.24.7 和 Strapi v4。我嘗試使用電子郵件和密碼登入;雖然我成功登入並且有 token 和使用者資料,但 session 返回 null。請看看我的程式碼並幫我解決這個問題。提前感謝你。

這是 app/api/auth/[...nextauth]/route.ts

import { options} from "@/app/services/auth";
import NextAuth from "next-auth";

// import the authOptions you have created inside the auth.js file
const handler = NextAuth(options);
export { handler as GET, handler as POST };

這是 auth.tsx:

import CredentialsProvider from "next- 
  auth/providers/credentials";
import axios from "axios";
export const options = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: {
          label: "Username:",
          type: "text",
          placeholder: "Username",
        },
        password: {
          label: "Password:",
          type: "password",
          placeholder: "Enter your password",
        },
      },
      authorize: async (credentials) => {
        return axios.post(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/local`, 
       {
          identifier: credentials?.username,
          password: credentials?.password,
       })
       .then(async (e) => {
         const { jwt, user } = e.data;
         if (jwt) {
           const roles = await axios
            .get(
              `${process.env.NEXT_PUBLIC_API_URL}/api/users/me?populate=role`,
              {
                headers: { Authorization: `Bearer ${jwt}` },
              }
            )
            .then(({ data }) => {
              return data;
            })
            .catch((e) => {
              console.log("catch", e);
              return [];
            });
         
          return {
            ...user,
            name: user.first_name + ' ' + user.last_name,
            jwt,
            roles,
            id: user.id,
          };
        }
      })
      .catch((e) => {
        return null;
      });
    },
  }),
],
pages: {
  signIn: "/signin",
},
callbacks: {
  jwt: ({ token, user }:{token:any,user:any}) => {
  
  console.log(user,'..................')
    if (token) {
      token.id = token.id;
      token.roles = token.roles;
      token.jwt = token.jwt;
    }
    return token;
  },
  session: ({ session, token }:{session:any,token:any}) => {
    session.user.id = token.id;
    session.user.roles = token.roles;
    session.user.jwt = token.jwt;
 
    return session;
  },
 },
};

這是我在 Login.tsx 表單中的 submit 函數。我在這裡 console.log(session, "................."),它返回 null。

const onSubmit: SubmitHandler<IFormValues> = async (data) => {
      const signedIn = await signIn("credentials", {
          username: data?.userName,
          password: data?.password,
          redirect: false,
          callbackUrl,
      });
      // here the session is null
      console.log(signedIn, session, "................");
      if (!signedIn?.error) {
        router.push("/profile");
        return;
      }
  };