Next Auth getSession API 在生产中用于 getServerSideProps 函数时调用失败

Next Auth getSession API call fails when used in getServerSideProps function on production

getSession 在客户端运行正常,但在服务器端运行不正常

在服务器端调用时,我在服务器上收到此错误:

error -> https://next-auth.js.org/errors#client_fetch_error session FetchError: request to https://nextauth_url_internal/api/auth/session failed, reason: getaddrinfo ENOTFOUND nextauth_url_internal

服务器端代码

export const getServerSideProps = async (context) => {
  const { req } = context;
  try {
    const session = await getSession({ req });
    console.log({ session });
    if (!session) return { redirect: { destination: '/', permanent: false } };
    return { props: { session } };
  } catch (error) {
    console.log(error);
  }
};

您似乎没有配置 NEXTAUTH_URL environment variable

你能试试这个吗:删除 .next 构建文件夹并通过 运行 npm run build 创建一个新构建。

然后重试。

在您的 NextAuth 函数中添加一个秘密选项

export default NextAuth({
   // Configure one or more authentication providers
   providers: [
      GoogleProvider({
         clientId: process.env.GOOGLE_CLIENT_ID,
         clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      }),
      // ...add more providers here
   ],
   secret: process.env.SECRET,
   pages: {
      signIn: "/auth/signin",
   },
   callbacks: {
      async session({ session, token, user }) {
         session.user.username = session.user.name
            .split(" ")
            .join("-")
            .toLocaleLowerCase();

         session.user.uid = token.sub;
         return session;
      },
   },
});