如何在nextjs中的服务器组件和客户端组件上使用Env变量

jdgnovmf  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(393)

我用的是nextjs app Dir。我需要发送电子邮件,我用nodemailer发送,我需要使用服务器组件,因为你不能用客户端发送。
我在这个项目中使用typescript,我有一些问题,使用的功能是服务器端到客户端。
我所做的
1.我创建了一个发送电子邮件并接受类型参数的函数,其中重要的一个是toEmail,它应该是一个字符串。我使用'use server',因为我有其他错误,解决方案是使其成为服务器组件。

'use server'
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
//   host: 'smtp.ethereal.email',
//   port: 587,
    service: 'gmail',
    secure: false,
        auth: {
            user: process.env.EMAIL,
            pass: process.env.EMAIL_PASSWORD,
        },
});

export const sendEmail = async (toEmail: string, subject: string, html: string) => {
    await transporter.sendMail({
        from :      process.env.EMAIL_ADMIN_QUOTE_RECEIVER,
        to:         toEmail,
        subject:    subject,
        html:       html
    });
};
```;


2. Secondly, I created the client component that gets the state and finally the one that sends the email. However, Because I want to use env variables, the `toEmail` parameter cannot accept `string | undefined`, because it should be strictly a string. If i log the `process.env.EMAIL_ADMIN_QUOTE_RECEIVER` in the console, I get the result in the server console, but in the browser is undefined.... 
This component is a 'use client' component

Here is the function:

const handleSendQuote = async(event:System. out. println();

const emailHTML = render(<NewQuoteReceived 
    name={fullName}                         dateRequired={dateRequired}
    vechNeeded={vechiclesRequired}          serviceReq={service}
    phone={phoneNumber}                     email={email} 
    details={details} />)
  
  
await sendEmail(process.env.EMAIL_ADMIN_QUOTE_RECEIVER, 'New quote received', emailHTML);
alert('Sent');
 
clearState();

}

klsxnrf1

klsxnrf11#

  1. toEmail真的需要成为sendEmail函数中的参数吗?看起来它总是相同的值,你可以在后端硬编码它。
    1.如果你真的想把你的环境变量暴露给客户端,你应该用NEXT_PUBLIC_作为前缀:
    https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#exposing-environment-variables-to-the-browser

相关问题