Mailfully logo

Calling the API from a browser

A browser fetch to the Mailfully API fails with a CORS error. Call Mailfully from your server instead of your frontend.

A browser fetch to api.mailfully.com fails with a CORS error because the API sends no CORS headers. A key in frontend code is readable by every visitor, so call Mailfully from your server.

Call it from your server

Put a route on your own server that holds the key, validates its own input and calls Mailfully. The browser calls your route.

import { Mailfully } from "mailfully";

const mailfully = new Mailfully({ apiKey: process.env.MAILFULLY_API_KEY ?? "" });

export async function POST(request: Request) {
  const { email } = await request.json();

  if (typeof email !== "string" || !email.includes("@")) {
    return new Response("Invalid email", { status: 400 });
  }

  const { data, error } = await mailfully.emails.send({
    from: "orders@mail.acme.com",
    to: email,
    subject: "Your order shipped",
    text: "Order 4212 shipped.",
  });

  if (error !== null) {
    return new Response(error.message, { status: error.statusCode ?? 500 });
  }

  return Response.json(data);
}

Give the key that route holds only the scopes it needs. See API key security.

If a key has already reached a browser

Treat it as leaked. See A leaked API key.