Mask Email Addresses for Logs

Mask the local part of email addresses while preserving the domain, with short-address handling and an option to hide subdomains.

JavascriptSecurity Boundaries

Code

javascriptsnippet
65 lines
export function maskEmail(email, options = {}) {
  if (typeof email !== "string") {
    throw new TypeError("email must be a string");
  }
  const { maskDomain = false } = options;
  const address = email.trim();
  if (address.length === 0 || address.length > 254) {
    throw new Error("invalid email length");
  }
  if (/\s/.test(address)) {
    throw new Error("invalid email address");
  }

  const atIndex = address.indexOf("@");
  if (
    atIndex <= 0 ||
    atIndex !== address.lastIndexOf("@") ||
    atIndex === address.length - 1
  ) {
    throw new Error("invalid email address");
  }

  const local = address.slice(0, atIndex);
  const domain = address.slice(atIndex + 1);
  if (
    !domain.includes(".") ||
    domain.startsWith(".") ||
    domain.endsWith(".") ||
    domain.includes("..")
  ) {
    throw new Error("invalid email domain");
  }

  let maskedLocal;
  if (local.length === 1) {
    maskedLocal = "*";
  } else if (local.length === 2) {
    maskedLocal = `${local[0]}*`;
  } else {
    maskedLocal = `${local[0]}***${local[local.length - 1]}`;
  }

  let maskedDomain = domain;
  if (maskDomain) {
    const labels = domain.split(".");
    maskedDomain = labels
      .map((label, index) =>
        index === labels.length - 1 ? label : "*".repeat(Math.max(1, label.length)),
      )
      .join(".");
  }

  return `${maskedLocal}@${maskedDomain}`;
}

console.log(maskEmail("alice.smith+dev@example.com"));
console.log(maskEmail("ab@example.com"));
console.log(maskEmail("a@example.com"));
console.log(maskEmail("alice@mail.example.com", { maskDomain: true }));

try {
  maskEmail("not-an-email");
} catch (error) {
  console.log(error.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

a***v@example.com
a*@example.com
*@example.com
a***e@****.*******.com
invalid email address

How it works

One way to read it: the function maskEmail, doing all the work.

Invalid states are rejected up front: it throws TypeError and Error instead of continuing with bad data.

What to watch for

  • The guard typeof email !== "string" short-circuits the flow with an early throw when its condition holds.

Using it

The entry-point signature is export function maskEmail(email, options = {})

The surface worth importing is maskEmail; the helpers around it are private to the snippet.

Key statements

throw new TypeError("email must be a string");
throw new Error("invalid email address");
throw new Error("invalid email length");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
It throws `TypeError` and `Error` before any real work runs, via the guard `typeof email !== "string"` — handle it at the call site or let it propagate deliberately.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `maskEmail` at load time.