I'm following the setup guide for Sendgrid on Node.js (https://app.sendgrid.com/guide/integrate/langs/nodejs), but I keep getting an API key error.
This is my code:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Sending with Twilio 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)
.then(() => console.log('send mail success'))
.catch(console.log);
My API key is setup correctly in my .env file:
SENDGRID_API_KEY=SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o
This is the error message I'm getting:
API key does not start with "SG.".
ResponseError: Unauthorized
at BE-KeyCon/node_modules/@sendgrid/client/src/classes/client.js:133:29
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 401,
response: {
headers: {
server: 'nginx',
date: 'Fri, 12 Jun 2020 21:31:08 GMT',
'content-type': 'application/json',
'content-length': '116',
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] }
}
}
If I set the API key as a string, like so:
sgMail.setApiKey('SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o')
Then it works. But obviously I can't leave it like this for security reasons. Any idea why it's behaving this way and how I might fix it?