New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 4 Nov 2026

Send Email from a React App Without Exposing Credentials: The Backend Pattern

Why a React app must never hold SMTP passwords or email API keys, and the backend-for-frontend pattern that fixes it: a small server endpoint, validation, rate limiting, CORS and safe key handling, with working Express code.

SM
Written by Sofia Marino
Technical Support Lead
Reviewed by Tomasz Kowalski
  • Published23 May 2024
  • Read time8 min
  • Length1,584 words
Share this guide

A React app cannot send email securely by itself. Everything that ships to the browser, including values in .env files that are bundled by Vite, Create React App or Next.js public variables, can be read by any visitor with developer tools. If your SMTP password or email API key is in that bundle, treat it as public, and rotate it.

The fix is the backend pattern: the browser sends form data to a small server endpoint you control, and that server holds the credentials and talks to the mail system. This guide shows the pattern, a complete Express example, and the controls that stop your endpoint from becoming a spam gateway.

RuleNo secret ever goes into client-side code or a public environment variable
PatternReact form posts to your own endpoint; the server sends the email
Endpoint controlsValidation, rate limiting, fixed recipient, CORS allowlist, bot check
If a key leakedRevoke and rotate it immediately, then review sending logs

Why client-side credentials are never safe

Bundlers inline environment variables with a public prefix (VITE_, REACT_APP_, NEXT_PUBLIC_) into the JavaScript the browser downloads. Obfuscation, minification and base64 do not help: a request your app makes from the browser, including its headers and body, is visible in the network tab. Anyone who copies an API key from there can send as you until you revoke it.

The damage is concrete. An attacker can send phishing or spam through your account, which damages your domain and IP reputation, can trigger blocklisting and may get your account suspended. See API key security for how to scope and rotate keys.

Where the secret livesSafe?Why
React component or hard-coded stringNoShipped to every visitor
VITE_ / REACT_APP_ / NEXT_PUBLIC_ variableNoInlined into the bundle at build time
Server environment variableYesNever leaves your server
Serverless function environment variableYesStays in the function runtime
Public Git repositoryNoBots scan for keys within minutes of a push
Proxy that adds the key but accepts any requestPartlyThe key is hidden, but the proxy can still be abused

The backend-for-frontend pattern

Your React app calls an endpoint on a server you control. The endpoint validates the request, decides the recipient and content, and then sends through SMTP or an HTTP API using credentials from its own environment. The browser only ever learns whether the request succeeded.

  1. The user submits the form in React.
  2. The app sends POST /api/contact with name, email and message as JSON.
  3. The server validates the fields, checks rate limits and bot signals.
  4. The server builds the message itself, using a fixed recipient and its own From address.
  5. The server calls the mail provider with its secret and returns a simple status.

The important design rule: the browser supplies content, the server decides everything that carries risk, namely the recipient, the From address and the credentials. If the client can choose the recipient, your endpoint is an open mail relay for the web.

A working Express endpoint

This example uses Express and Nodemailer over SMTP on port 587. Install with npm install express nodemailer express-rate-limit cors. Credentials come from the server environment.

// server.js
import express from 'express';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import nodemailer from 'nodemailer';

const app = express();
app.use(express.json({ limit: '20kb' }));
app.use(cors({ origin: ['https://www.example.com'] }));

const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 });

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: 587,
  secure: false, // STARTTLS on 587
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});

app.post('/api/contact', limiter, async (req, res) => {
  const { name, email, message, website } = req.body || {};
  if (website) return res.status(204).end(); // honeypot field filled by bots

  const clean = (s) => String(s || '').replace(/[\r\n]+/g, ' ').trim();
  const n = clean(name).slice(0, 100);
  const e = clean(email).slice(0, 200);
  const m = String(message || '').trim().slice(0, 5000);

  if (!n || !m || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)) {
    return res.status(400).json({ error: 'Invalid input' });
  }

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM,   // fixed, authenticated domain
      to: process.env.MAIL_TO,       // fixed, never from the client
      replyTo: e,
      subject: `Website message from ${n}`,
      text: m,
    });
    res.json({ ok: true });
  } catch (err) {
    console.error(err);
    res.status(502).json({ error: 'Could not send' });
  }
});

app.listen(3001);

And the React side, which contains no secrets and only knows a URL.

// ContactForm.jsx
import { useState } from 'react';

export default function ContactForm() {
  const [status, setStatus] = useState('idle');

  async function onSubmit(ev) {
    ev.preventDefault();
    setStatus('sending');
    const data = Object.fromEntries(new FormData(ev.target));
    const res = await fetch('/api/contact', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    setStatus(res.ok ? 'sent' : 'error');
  }

  return (
    <form onSubmit={onSubmit}>
      <input name="name" required />
      <input name="email" type="email" required />
      <textarea name="message" required />
      <input name="website" tabIndex="-1" autoComplete="off" style={{ display: 'none' }} />
      <button disabled={status === 'sending'}>Send</button>
      {status === 'sent' && <p>Thanks, we will reply soon.</p>}
      {status === 'error' && <p role="alert">Something went wrong.</p>}
    </form>
  );
}

If you prefer an HTTP API to SMTP, the server code changes only in the sending step: a fetch to the provider with a Bearer key held in the server environment. Confirm field names in the API reference. The trade-offs are covered in SMTP versus API.

Controls that stop abuse

  • Fixed recipient. Read the destination from server configuration. If you must support several recipients, accept an identifier and map it on the server.
  • Fixed From address. Use an address on a domain you have authenticated. Put the visitor's address in Reply-To only.
  • Header injection defence. Strip carriage returns and line feeds from any value that reaches a header. See header injection.
  • Rate limiting. Limit by IP and, if you have accounts, by user. Five requests per fifteen minutes is a sensible starting point for a contact form, tune it to your traffic.
  • Bot checks. A honeypot field catches simple bots; a CAPTCHA or proof-of-work challenge handles the rest. See signup bot protection.
  • CORS allowlist. Allow only your own origin. CORS does not stop scripts and curl, it only governs browsers, so it complements rather than replaces the other controls.
  • Size limits. Cap the JSON body and the message length.
  • Scoped credentials. Use a key that can only send, not manage the account.

Alternatives to running your own server

You do not need a long-running server. A serverless function (on any platform that supports them) or a framework route such as a Next.js route handler works the same way: the function holds the secret, the React code calls it. For Next.js specifics, see sending from Next.js. Some form-backend services accept a public form identifier instead of a secret; that is a legitimate design, but check how they prevent abuse and where submissions are stored.

Avoid third-party widgets that ask you to paste your SMTP password or API key into client code. Avoid mailto: links as a substitute for a form if you need to capture and track submissions; they depend on the visitor having a configured mail client.

What to tell the user and what to log

Keep the visible behaviour simple. On success show a short confirmation; on failure show a generic message and let the user retry. Do not echo provider error text to the browser, because it can reveal configuration details. On the server, log the request identifier, the outcome and the provider response code, but not the message body or the sender's personal details unless you need them and have said so in your privacy notice.

Also decide what happens when sending fails after you have already told the user it worked. For a contact form, a failure that is logged and retried is acceptable. For anything that matters more, such as an order confirmation, store the message in a queue first and send from a worker, so a temporary provider outage does not lose it. See mail queues.

If a key has already been exposed

  1. Revoke or rotate the credential at the provider now. Do not wait to see if it was used. See rotating an API key.
  2. Review recent sending activity for messages you did not send. See responding to a compromised sending account.
  3. Remove the key from the code and from Git history if it was committed; deleting the file in a new commit is not enough.
  4. Move the secret to server-side configuration and redeploy.
  5. Watch bounce and complaint rates for several days, since abuse can leave reputation damage.

Troubleshooting

SymptomLikely causeFix
CORS error in the browser consoleOrigin not in the allowlist, or preflight not handledAdd your site origin to the cors config
404 on /api/contact in developmentDev server has no proxy to the backendAdd a proxy rule in the dev server or call the full backend URL
400 Invalid input for valid dataBody not parsedEnsure express.json() is registered before the route
429 Too Many Requests while testingRate limit reachedWait for the window, or raise the limit for development only
Server logs 535 errorWrong SMTP credentialsRe-check. See fixing 535 errors
Messages sent but land in spamFrom domain not authenticatedSet up SPF, DKIM and DMARC

Next steps

Once the endpoint works, add delivery tracking: handle bounce and complaint events so that you stop sending to addresses that reject you. See delivery event webhooks. Then run a test in a staging environment before you point the form at a real inbox.

Keep credentials on the server Send from your backend through the MigoSMTP relay or email API with a scoped key.

Explore the email API

References and further reading

Frequently asked questions

Can I hide an API key in a React environment variable?

No. Variables bundled by Vite, Create React App or Next.js public settings are shipped to the browser and can be read by anyone. Keep keys on a server.

Do I need a full backend just to send a contact form?

No. A single serverless function or route handler that holds the secret and sends the message is enough.

Does CORS protect my email endpoint?

Only partly. CORS restricts browsers, not scripts or curl, so you still need validation, rate limiting and a fixed recipient.

Should the client be allowed to choose the recipient?

No. Take the recipient from server configuration, otherwise your endpoint becomes an open relay for spam.

What should I do if my key was committed to a public repository?

Revoke it immediately, create a new one, store it server-side and review your sending logs for misuse.

Topics#react#security#api keys#backend#express#javascript
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales