在 getServerSideProps 中使用 EmailProvider 获取 NextAuth 会话会抛出 fs“找不到模块”

问题描述 投票:0回答:1

我正在尝试从

getServerSideProps
中的服务器端调用获取 NextAuth 会话,并且我正在将
EmailProvider
与 NextAuth 一起使用。我正在按照 NextAuth 的文档 中的示例从
getServerSideProps
.

获取会话

[...nextauth].ts]
配置文件中,我使用的是
EmailProvider
.

// pages/api/auth/[...nextauth].ts

import NextAuth from 'next-auth';
import EmailProvider from 'next-auth/providers/email';

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    EmailProvider({ ... }),
  ],
};

export default NextAuth(authOptions);

在前端组件中,我尝试这样获取会话:

// components/MyComponent.tsx

import { authOptions } from '@auth/[...nextauth]';

export const getServerSideProps = async ({ req, res }) => {
  const serverSession = await getServerSession(req, res, authOptions);
  
  return {
    props: { serverSession },
  };
};

我什至在

next.config.js
中添加了 webpack 配置以在客户端上忽略仅服务器代码:

// next.config.js
module.exports = {
  webpack: (config, { isServer, webpack }) => {
    if (!isServer) {
      config.plugins.push(
        new webpack.IgnorePlugin({ resourceRegExp: /^\/pages\/api\/auth\/$/ })
      );
    }
  }
}

问题是,当我将

import { authOptions } from '@auth/[...nextauth]';
添加到我的前端组件文件时,它会抛出一个编译错误:

// compilation error
error - ./node_modules/nodemailer/lib/dkim/index.js:10:0
Module not found: Can't resolve 'fs'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/nodemailer/lib/mailer/index.js
./node_modules/nodemailer/lib/nodemailer.js
./node_modules/next-auth/providers/email.js
./pages/api/auth/[...nextauth].ts
./components/MyComponent.tsx
./pages/index.tsx

我想这是我在

[...nextauth]
中导入
MyComponent
时的预期行为,它导入
EmailProvider
,它导入
nodemailer
,而
nodemailer
导入
fs
。由于
MyComponent
在客户端上运行,它会抛出错误,因为
fs
模块在客户端上不可用。

所以我尝试了一些东西:

  • "fs": false
    添加到我的
    package.json
    源在这里)这可以作为创可贴解决方案,但随后需要将更多模块添加到
    package.json
    ,我陷入了一个最终阻止
    prisma
    的兔子洞正在使用中。
  • authOptions
    内导入
    getServerSideProps
    example)。这并不影响错误。

还有其他想法吗?谢谢!

node.js typescript nodemailer next-auth
1个回答
0
投票

啊所以 components 不能做服务器端渲染(SSR),只有 pages 可以。这是更多文档.

所以为了解决这个问题,我将

getServerSideProps
移动到一个页面(例如
pages/index.tsx
pages/
的根目录中的任何其他页面)。代码看起来是一样的,复制在下面,但是代码所在的文件不同。

// components/MyComponent.tsx <-- this is wrong
// ^^ IT SHOULD NOT BE A COMPONENT

// pages/index.tsx <-- or whatever page you're using
// ^^ IT SHOULD BE A PAGE INSTEAD OF A COMPONENT

import { authOptions } from '@auth/[...nextauth]';

export const getServerSideProps = async ({ req, res }) => {
  const serverSession = await getServerSession(req, res, authOptions);
  
  return {
    props: { serverSession },
  };
};
© www.soinside.com 2019 - 2024. All rights reserved.