Integrations · Frameworks and SDKs

Validate emails in Astro forms

A small package for Astro servers that checks the email address of a sign-up, contact or newsletter form post before your code runs: in an endpoint, in middleware for the paths you list, or inside an action's handler. It refuses addresses that cannot receive email and throwaway inboxes, and by default never stops a real person from signing up when our API cannot answer.

// src/middleware.ts
import { emailValidationMiddleware } from '@email-validation/astro';

export const onRequest = emailValidationMiddleware({ paths: ['/api/signup'] });

Install

The package is not on npm yet. Download it here and install it with npm:

  1. Download email-validation-astro-1.0.0.tgz (MIT licence) into your Astro project.

  2. Install it:

    npm install ./email-validation-astro-1.0.0.tgz

    To keep it in your dependencies, commit the file to your repository: npm records its path in package.json.

  3. Create an API key on the API keys page with the permission "Validate addresses", and give it a daily credit cap to limit what a busy form can spend. Set it on your server as EV_API_KEY; never put it in code or in a client script (in a browser bundle the package throws at once).

It needs Astro 7 and has no dependencies of its own. The route must be rendered on demand (an adapter, and export const prerender = false unless your output is server): a prerendered page never sees a form post.

Use it

An endpoint. Wrap the handler: the check reads a clone of the request, so your handler reads the body as usual.

// src/pages/api/signup.ts
import type { APIRoute } from 'astro';
import { withEmailValidation } from '@email-validation/astro';

export const prerender = false;

export const POST: APIRoute = withEmailValidation(async ({ request }) => {
  const data = await request.formData();
  // … create the account
  return Response.json({ ok: true });
});

Middleware for several paths. A POST to a listed path (exact, or a regular expression) is checked first; a refused one never reaches the route; otherwise the route runs with the outcome in locals.emailCheck (null when the request was not checked): context.locals.emailCheck in an endpoint, Astro.locals.emailCheck in an .astro page. It fits inside Astro's sequence(…) with your own middleware.

// src/middleware.ts
import { emailValidationMiddleware } from '@email-validation/astro';

export const onRequest = emailValidationMiddleware({ paths: ['/api/signup', /^\/api\/invite\//] });

In an action. Actions are never checked by the middleware (their client expects the action's own answer), so call the check in the handler:

// src/actions/index.ts
import { ActionError, defineAction } from 'astro:actions';
import { z } from 'astro/zod';
import { createEmailCheck } from '@email-validation/astro';

const checkEmail = createEmailCheck();

export const server = {
  newsletter: defineAction({
    accept: 'form',
    input: z.object({ email: z.email() }),
    handler: async ({ email }) => {
      const outcome = await checkEmail(email);
      if (outcome.stop) throw new ActionError({ code: 'BAD_REQUEST', message: outcome.message ?? undefined });
      // …
    },
  }),
};

A refused address gets HTTP 422: a JSON error {"error":{"code","message","status"}} for a JSON request, else the message as plain text. onStop(outcome, request) returns your own response instead. The codes are email_invalid, email_disposable, email_catch_all and email_unknown. With failOpen: false, a check that cannot finish is refused with HTTP 503 and email_unavailable instead.

Settings

withEmailValidation(handler, options), emailValidationMiddleware(options) and createEmailCheck(options) take:

OptionDefaultWhat it does
apiKeyEV_API_KEYyour key (for example from astro:env/server)
regionEV_REGION, else useu sends checks to https://api-eu.email-validation.org
stopOn['invalid', 'disposable']the statuses refused: any of invalid, disposable, catch_all, unknown
failOpentruefalse: a check that cannot finish is refused with 503 and email_unavailable
timeoutMs8000how long the request waits for our answer; nothing is retried
apiTimeout5seconds our API may spend on the check (5 to 15)
messagesthe package'syour own sentences, by verdict
onResultnonecalled once with each outcome (no address, no key)

The endpoint wrapper and the middleware also take field (the form field or JSON key, default email), maxBodyBytes (default 1 MiB; a larger body goes through unchecked), methods (default ['POST']) and onStop; the middleware needs paths.

  • Which statuses are refused. invalid and disposable by default; valid always goes through. catch_all and unknown pass unless you add them: see what each status means. An unknown caused by our own timeout or error never stops anyone.
  • When the check cannot finish (a timeout, a network error, our error, no key, a 429 pause), the request goes on as if the address were fine. After a 429 or 503 answer no check is sent for the Retry-After time.
  • Never logged. The address and the key never reach a log, an error or the outcome.
  • EU data residency. Set region: 'eu' (or EV_REGION=eu); the same key works on both.

Costs

One POST /v1/validate per checked request. Each completed check costs one credit. Results with the status unknown are free, and so are the test addresses: post disposable@sandbox.email-validation.org (refused) and accepted@sandbox.email-validation.org (passes) at no cost. On a form that mails the address (a sign-up, a welcome), try only the one that is refused: one that passes reaches your code, and its mail would bounce. See credits and billing.

More on Astro

Updated · Maintained by: Email Validation LLC

Need help? Contact support, or ask the help chat. Something wrong or missing on this page? Tell us