2

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({
//   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: 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();

}

daniel sas
  • 257
  • 2
  • 9

1 Answers1

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

Igor Danchenko
  • 1,980
  • 1
  • 3
  • 13
  • The ideal case is that function to be reused in multiple components. Because The website will be based on sending emails... So i guess I will hardcode it, because i only need limited env variables to be exposed – daniel sas May 25 '23 at 16:19