Home > Software design >  How to fix SendGrid CORS error from React Js application?
How to fix SendGrid CORS error from React Js application?

Time:10-17

I have a react application and I am trying to send an email using SendGrid, I am using @sendgrid/mail to send an email. But it shows this error when I sent an email and the email doesn't send.

I got this error

Access to XMLHttpRequest at 'https://api.sendgrid.com/v3/mail/send' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not equal to the supplied origin.

My code looks like this

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey("key");

const message = {
      to: "to email",
      from: "from email",
      subject: "subject",
      html: `
      <p><strong>Hello/strong></p>`,
    };

    Gmail
      .send(message)
      .then(() => {
        console.log("Email Sent!");
      })
      .catch((error) => {
        console.error("Error: ", error);
      });

Please help to fix this!

CodePudding user response:

I would not recommend doing that as it means you would expose your API key.

But there's an alternative if you say you don't want/need a backend. You can use Twilio Functions to implement the code to send the SMS and protect the Function either with a JWT token or (for testing) basic auth.

  • Related