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

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

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.
  1. 'use server'
  2. import nodemailer from 'nodemailer';
  3. const transporter = nodemailer.createTransport({
  4. service: 'gmail',
  5. secure: false,
  6. auth: {
  7. user: process.env.EMAIL,
  8. pass: process.env.EMAIL_PASSWORD,
  9. },
  10. });
  11. export const sendEmail = async (toEmail: string, subject: string, html: string) => {
  12. await transporter.sendMail({
  13. from : process.env.EMAIL_ADMIN_QUOTE_RECEIVER,
  14. to: toEmail,
  15. subject: subject,
  16. html: html
  17. });
  18. };
  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:

  1. const handleSendQuote = async (event: FormEvent) => {
  2. event.preventDefault();
  3. const emailHTML = render(<NewQuoteReceived
  4. name={fullName}
  5. dateRequired={dateRequired}
  6. vechNeeded={vechiclesRequired}
  7. serviceReq={service}
  8. phone={phoneNumber}
  9. email={email}
  10. details={details} />)
  11. await sendEmail(process.env.EMAIL_ADMIN_QUOTE_RECEIVER, 'New quote received', emailHTML);
  12. alert('Sent');
  13. clearState();
  14. }
英文:

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.
  1. &#39;use server&#39;
  2. import nodemailer from &#39;nodemailer&#39;;
  3. const transporter = nodemailer.createTransport({
  4. // host: &#39;smtp.ethereal.email&#39;,
  5. // port: 587,
  6. service: &#39;gmail&#39;,
  7. secure: false,
  8. auth: {
  9. user: process.env.EMAIL,
  10. pass: process.env.EMAIL_PASSWORD,
  11. },
  12. });
  13. export const sendEmail = async (toEmail: string, subject: string, html: string) =&gt; {
  14. await transporter.sendMail({
  15. from : process.env.EMAIL_ADMIN_QUOTE_RECEIVER,
  16. to: toEmail,
  17. subject: subject,
  18. html: html
  19. });
  20. };
  21. ```;
  22. 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....
  23. This component is a &#39;use client&#39; component
  24. Here is the function:

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

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

}

  1. </details>
  2. # 答案1
  3. **得分**: 1
  4. 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."
  5. 2) "If you really want to expose your environment variable to the client side, you should prefix it with `NEXT_PUBLIC_`:
  6. https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#exposing-environment-variables-to-the-browser"
  7. <details>
  8. <summary>英文:</summary>
  9. 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.
  10. 2) If you really want to expose your environment variable to the client side, you should prefix it with `NEXT_PUBLIC_`:
  11. https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#exposing-environment-variables-to-the-browser
  12. </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:

确定