DEV Community

Nuno Faria
Nuno Faria

Posted on

Sendgrid API + NodeJS project template

Projects quickly reach a point where it is necessary to send emails, maybe a contact form or a password reset feature.

It is possible to use the Sendgrid Mail API v3 directly on a website but it is entirely not recommended since it means exposing the Sengrid API key.

A project template

The sendgrid-nodejs-endpoint project is meant to be used as a template - it provides the following features out-of-the-box:

  • configurable allowed origins
  • configurable allowed recipients
  • Basic or Digest authentication

Configured by specifying environment variables when deployed (or a .env file) and a passfile with authentication data if necessary.

PORT=3001
SENDGRID_API_KEY=<Sendgrid API key>

FROM=sender@mail.com
ALLOWED_RECIPIENTS=recipient1@mail.com recipient2@mail.com

ALLOWED_ORIGINS=http://example.com

AUTH_SCHEME=Digest
AUTH_REALM=test-realm
AUTH_PASSFILE=/path/users.passfile
Enter fullscreen mode Exit fullscreen mode

REST Endpoints

"/" root endpoint

GET endpoint responds with "Hello World!" message:

> GET /
< 200 OK
{
  "message": "Hello World!"
}
Enter fullscreen mode Exit fullscreen mode

"/mail" endpoint

POST endpoint receives body with JSON object and uses the same object API as Sendgrid NodeJS API.

> POST /mail
{
    "to": "recipient@mail.com",
    "subject": "test sendgrid client",
    "text": "test sendgrid client",
    "html": "test sendgrid client"
}

< 200 OK
Enter fullscreen mode Exit fullscreen mode

Top comments (0)