Trying to figure our why Sendgrid's email API integration with Firebase Functions is returning "API key does not start with SG."

Viewed 334

I'm trying to integrate Sendgrid's Email API with my Firebase webapp. Here is what I've done:

1 - Installed Sendgrid's Mail package

npm install @sendgrid/mail

2 - Created an API Key on my Sendgrid Account

3 - Assigned the API Key to an environment variable using Firebase's environment configuration:

firebase functions:config:set sendgrid.key=SG.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxx_xxxxxx_xxxxxxxxxxxxxxx 

4 - checked to see if the environment variable was correctly assigned:

firebase functions:config:get

result:

log of firebase environment variable

5 - imported sendgrid mail and set API key:

import * as sgMail from '@sendgrid/mail';

const API_KEY = functions.config().sendgrid.key

const TEMPLATE_ID = functions.config().sendgrid.template
sgMail.setApiKey(API_KEY);

6 - created a new user trigger to send a test email

export const welcomeEmail = functions.auth.user().onCreate(user => {

    const msg = {
        to: user.email,
        from: 'contato@mycompanydomain.com.br',
        templateId: TEMPLATE_ID,
        dynamic_template_data: {
            subject: 'test subject!',
            name: user.displayName,
        },
    };

    return sgMail.send(msg);

})

7 - Deployed firebase functions:

firebase deploy --only functions

After doing this I'd expect that at least the API key would be set correctly, but I keep getting the following error from firebase functions log:

enter image description here

I can't figure out what is wrong. I've tried a few things:

1- creating a new api key and starting the process all over.

2- pasting the API directly into the sgMail.setApiKey() method. like:

sgMail.setApiKey("SG.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxx_xxxxxx_xxxxxxxxxxxxxxx")

All of which gave the same "API key does not start with SG" error.

Can you guys help me figure out what's wrong?

Versions

"@sendgrid/mail": "^7.2.1",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.8.0"

Thank you so much

1 Answers

For does who had the same problem, I solved it by using the new firebase package and importing the config from firebase-functions. So my code looks like this:

import functions, { config } from "firebase-functions";
import sendgrid from "@sendgrid/mail";
const MY_SENDGRID_API_KEY = config().sendgrid.key;
sendgrid.setApiKey(MY_SENDGRID_API_KEY);
Related