如何在 Next.js 中在服务器组件和客户端组件中使用环境变量

huangapple go评论79阅读模式
英文:

How to use Env variables on server components and also client components in nextjs

问题

I am using nextjs app Dir. I need to send emails which I am sending with nodemailer, and I am required to use server components since you cannot send with clientside.

I am using typescript in this project and I have some issues using a function that is server side to a client side.

What I done

  1. I created a function that sends email and accepts parameters with types, the important one being toEmail one which should be a string only. I used 'use server', because I had other errors where the solution was to make it a server component.
'use server'
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
    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
    });
};
  1. 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: FormEvent) => {
    event.preventDefault();

    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();
}
英文:

I am using nextjs app Dir. I need to send emails which I am sending with nodemailer, and I am required to use server components since you cannot send with clientside.

I am using typescript in this project and I have some issues using a function that is server side to a client side.

What I done

  1. I created a function that sends email and accepts parameters with types, the important one being toEmail one which should be a string only.
    I used &#39;use server&#39;, because I had other errors where the solution was to make it a server component.
&#39;use server&#39;
import nodemailer from &#39;nodemailer&#39;;


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


export const sendEmail = async (toEmail: string, subject: string, html: string) =&gt; {
    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 &#39;use client&#39; component

Here is the function:

const handleSendQuote = async (event: FormEvent) => {
event.preventDefault();

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

}


</details>


# 答案1
**得分**: 1

1) "Does `toEmail` really need to be an argument in your `sendEmail` function? Seems like it's going to be the same value all the time, and you can hard-code it on the backend."

2) "If you really want to expose your environment variable to the client side, you should prefix it with `NEXT_PUBLIC_`:

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#exposing-environment-variables-to-the-browser"

<details>
<summary>英文:</summary>

1) Does `toEmail` really need to be an argument in your `sendEmail` function? Seems like it&#39;s going to be the same value all the time, and you can hard-code it on the backend.

2) If you really want to expose your environment variable to the client side, you should prefix it with `NEXT_PUBLIC_`:

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#exposing-environment-variables-to-the-browser

</details>



huangapple
  • 本文由 发表于 2023年5月26日 00:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定