Maja Šveljo
Maja Šveljo

Reputation: 63

Firebase SendGrid error on sending email via Firebase functions - Error: Bad Request

I'm using Firebase and SendGrid and I'm using Firebase functions. I'm trying to send an email when a new user is created. When I trigger the function, I get the following error:

 firestoreEmail: Function execution started
2019-09-10T08:13:49.245Z I firestoreEmail: { Error: Bad Request
    at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)
    at Request.self.callback (node_modules/request/request.js:185:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (node_modules/request/request.js:1161:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
  code: 400,
  message: 'Bad Request',
  response: 
   { headers: 
      { server: 'nginx',
        date: 'Tue, 10 Sep 2019 08:13:49 GMT',
        'content-type': 'application/json',
        'content-length': '365',
        connection: 'close',
        'access-control-allow-origin': 'https://sendgrid.api-docs.io',
        'access-control-allow-methods': 'POST',
        'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
        'access-control-max-age': '600',
        'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
     body: { errors: [Array] } } } 

Here is my Index.js:

 const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


const SENDGRID_API_KEY = 'exact API key here because functions.config().sendgrid.key doesn't work, says sendgrid is undefined';

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

exports.firestoreEmail = functions.firestore
.document('Users/{userId}/Followers/{followerId}')
.onCreate(event => {

    const userId = "for now exact id";

    const db = admin.firestore()

    return db.collection('Users').doc(userId)
            .get()
            .then(doc => {
                const user = doc.data()

                const msg = {
                    to: "[email protected]",
                    from: '[email protected]',
                    subject: 'New Follower',
                };

                return sgMail.send(msg)
            })
            .then( () => console.log('email sent!') )
            .catch( (err) => console.log(err) )
}) 

P.S. I was following Fireship's tutorial https://www.youtube.com/watch?v=JVy0JpCOuNI&t=333s

Edit: These are the database SCs first image second image

Upvotes: 0

Views: 1010

Answers (1)

Maja Šveljo
Maja Šveljo

Reputation: 63

The problem was that the const msg was missing a templateId field, which is apparently mandatory if SendGrid is used. Here is the working snippet:

const msg = {
                    to: "[email protected]",
                    from: '[email protected]',
                    subject: 'New Follower',

                    templateId: 'd-03ff1102c6e647c08207f293fce1701f', <--- this was missing
                };

Upvotes: 2

Related Questions