Aurélien
Aurélien

Reputation: 1655

Send mail with Nuxt trough Sendgrid

I have a simple vuetify contact form and I want to send this forms by email. I have tried to use a method to send the email, but it does not work, because its on client side. So I get CORS issues.

Here's my code:

async send() {
  if (this.$refs.form.validate()) {
    try {
      const sgMail = require("@sendgrid/mail");
      sgMail.setApiKey(process.env.SENDGRID_API_KEY);
      const msg = {
        to: "[email protected]",
        from: "[email protected]",
        subject: "Sending with SendGrid is Fun",
        text: "and easy to do anywhere, even with Node.js",
        html: "<strong>and easy to do anywhere, even with Node.js</strong>"
      };
      sgMail.send(msg);
    }
  }
}

Is Express (or an other backend) required? Is there a way to make it work using a middleware?

EDIT

Apparently, it's just not possible: https://github.com/sendgrid/sendgrid-nodejs/issues/730

Upvotes: 1

Views: 4867

Answers (1)

yann_yinn
yann_yinn

Reputation: 144

The CORS policy from Sendgrid does not allow you to use their API from the browser (The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io').

Quoted from https://sendgrid.com/docs/for-developers/sending-email/cors/ :

In SendGrid's case, we do not allow our customers to make a browser-based call to our v3/mail/send endpoint. (...) You can create a server-based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.

You have to send the email from a server, which is a good thing since your API Key would be exposed by the browser otherwise.

If you are using Nuxt in SSR mode (with Node running), I guess you could create a "Server Middleware" ( https://nuxtjs.org/api/configuration-servermiddleware ), for example with a path like "/api/mail", that will send the email.

If you are using nuxt-generate to create a static site, you can use a "function as a service", with something like "https://webtask.io/", to create a small node script; that you can trigger by url from your client to send the email.

Upvotes: 1

Related Questions