Nodemailer OAuth2 2LO fails in Heroku deployment

Viewed 175
const { 
    EMAIL_FROM,
    EMAILS_TO,
    USER,
    GMAIL_CLIENT_ID,
    GMAIL_PRIVATE_KEY
} = process.env;
let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        type: 'OAuth2',
        user: USER,
        serviceClient: GMAIL_CLIENT_ID,
        privateKey: GMAIL_PRIVATE_KEY,
    }
}); 

This code send emails just fine in local environment.

I deployed to heroku and I am getting an error: Error: Can't generate token. Check your auth options

The heroku config vars are coming through correctly, best I can tell.

Could there be some sort of IP restriction Google has against heroku servers? Am I missing something here?

This is a gSuite account with a Google service account.

Thanks

1 Answers

OK. Figured this out but leaving this question here in case anyone makes this silly mistake.

Not a heroku issue. It is a .env issue.

Apparently, something breaks in the private key when passed as an env variable. Possibly it has to do with the line breaks...

Reagrdless, solutions that worked for me:

  1. when using a .env file, use double quotes: "-----BEGIN RSA PRIVATE KEY-----..."
  2. for heroku config vars, this didn't seem to work. So I wrapped it in a JSON string. {"key": "-----BEGIN RSA PRIVATE KEY-----...."} then in the app, JSON.parse(process.env.PRIVATE_KEY).key

If this helps someone in any way, you are very welcome!

Related