Node.js / Express

Secure Your SendGrid API Key in Node.js

A leaked SendGrid API key with Mail Send permission lets attackers send phishing emails from your verified domain, damaging your sender reputation permanently. KVE tokens are bound to your server — stolen tokens cannot send email from other hosts.

The Problem

This is what most Node.js codebases look like today. The SENDGRID_API_KEY key (SG.) lives directly in the process environment. If your repo, your CI logs, or your deployment config leaks — so does your key.

JavaScript
// email.js — real SendGrid key in environment
import sgMail from "@sendgrid/mail";

sgMail.setApiKey(process.env.SENDGRID_API_KEY); // SG.xxxxxxxx...

export async function sendWelcomeEmail(to, name) {
  await sgMail.send({
    from: "hello@myapp.com",
    to,
    subject: `Welcome to MyApp, ${name}!`,
    text: `Hi ${name}, thanks for signing up.`,
    html: `<p>Hi <strong>${name}</strong>, thanks for signing up.</p>`,
  });
}

The Fix

Send the request to the KeyVault Edge proxy at https://proxy.keyvaultedge.com with the provider's usual path, your kvt_ token in X-KV-Token and the provider's base URL in X-KV-Target. The proxy refuses requests whose Origin isn't on the token's allowed hosts, then injects your real SENDGRID_API_KEY, so it never sits in your app's environment.

JavaScript
// email.js — KVE_TOKEN is host-bound; SendGrid key not in process
export async function sendWelcomeEmail(to, name) {
  const response = await fetch("https://proxy.keyvaultedge.com/v3/mail/send", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-KV-Token": process.env.KVE_TOKEN, // kvt_... token, server-side only
      "X-KV-Target": "https://api.sendgrid.com",
      // Must match one of the token's allowed hosts
      Origin: process.env.APP_ORIGIN,
    },
    body: JSON.stringify({
      from: { email: "hello@myapp.com" },
      personalizations: [{ to: [{ email: to }] }],
      subject: `Welcome to MyApp, ${name}!`,
      content: [
        { type: "text/plain", value: `Hi ${name}, thanks for signing up.` },
        { type: "text/html", value: `<p>Hi <strong>${name}</strong>, thanks for signing up.</p>` },
      ],
    }),
  });

  if (!response.ok) throw new Error(`SendGrid error: ${response.status}`);
}

Setup in 4 steps

1

Create a KVE token for SendGrid

At keyvaultedge.com, create a token with your SG. API key. Set provider to SendGrid and add your Node.js server's hostname as an allowed host. Use a restricted SendGrid key (Mail Send only) rather than a Full Access key.

2

Update .env

Replace SENDGRID_API_KEY with KVE_TOKEN.

Shell
# .env
KVE_TOKEN=kvt_...your_token
APP_ORIGIN=https://yourdomain.com  # one of the token's allowed hosts
3

Replace @sendgrid/mail with native fetch

Remove the @sendgrid/mail import and sgMail.setApiKey call. Point the request at https://proxy.keyvaultedge.com with the provider's usual path (e.g. /v3/mail/send), send your token in X-KV-Token, the provider's base URL (https://api.sendgrid.com) in X-KV-Target, and an Origin header matching one of the token's allowed hosts. The body is the provider's normal request body; the proxy sets the provider's auth header with your real key and forwards it.

4

Restrict the token to Mail Send endpoints only

In the KeyVault Edge dashboard, set an endpoint path allowlist for your SendGrid token: only allow requests to /v3/mail/send. This prevents a compromised server from accessing your SendGrid contact lists or suppression groups.

What this protects, and what it doesn't

  • Your real SENDGRID_API_KEY stays at the edge, so it can't leak from your repo, logs, bundle or server environment.
  • The kvt_ token is still a credential. A copied token can be replayed by anyone who can send the right headers, including a fake Origin from a server. The protection is that each token has its own rate limits, monthly cost cap and endpoint scope, and you can revoke it in one click without rotating the provider key.
  • The cost cap is estimated from the usage the provider reports, so a request already in flight can overshoot it slightly.

Plans and limits are on the pricing page.

Start protecting your keys

Your SendGrid key is one leaked .env file away from being exploited. With KeyVault Edge the real key stays at the edge, and the token that replaces it is capped, scoped and revocable in one click.