Email, Verification Codes, and Third-Party Service Integration

Generate and consume one-time codes, configure email delivery, and bound external API waits

🎯 Introduction

By the end of this article, you will be able to send email verification codes and set expiration and failure handling for code verification and external API calls.

✉️ Configure email delivery

Node.js can send email with Nodemailer, which connects to a provider's SMTP service. SMTP is the protocol applications use to submit email.

Install the dependency for this section:

npm install nodemailer@10.2.1

Obtain the SMTP host, account, password, and allowed sender address from an enabled email service and store them in environment variables. Create mail.mjs:

mail.mjs
import nodemailer from 'nodemailer';

export const mailer = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: 465,
    secure: true,
    auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD },
    connectionTimeout: 5000,
    socketTimeout: 10000
});

host identifies the mail server; auth authenticates to it. Port 465 with secure: true establishes an encrypted connection. Follow the provider's settings if it requires another port. The timeouts bound connection establishment and idle socket waiting, avoiding indefinite waits during service failures.


🔢 Generate a one-time verification code

Generate a six-digit code on the server with a cryptographically secure random number:

send-code.mjs
import { randomInt } from 'node:crypto';
import { mailer } from './mail.mjs';

const code = String(randomInt(0, 1_000_000)).padStart(6, '0');

The result is a six-digit string that may begin with 0, so store and compare it as a string. Use it only for this verification. Do not log it or return it in the HTTP response that requests a code.


📤 Send it by email

Continue in send-code.mjs:

send-code.mjs
const result = await mailer.sendMail({
    from: process.env.MAIL_FROM,
    to: process.env.MAIL_TO,
    subject: 'Login verification code',
    text: `Your verification code is ${code}. It expires in 5 minutes.`
});
console.log(result.messageId);

MAIL_FROM is a provider-approved sender; MAIL_TO is the exercise recipient. Running node --env-file=.env send-code.mjs sends a real email and prints its message ID on success.

An ID means the service accepted submission, not that the email reached the inbox. Check provider delivery results for rejection, bounces, or spam classification. Production endpoints must validate recipients and limit sending frequency rather than expose unrestricted email delivery.


🗃 Verification codes need corresponding server records

A production code endpoint must save a verification record before sending. Store these fields in a database or shared cache:

InformationPurposeExample rule
Recipient emailBind the code to its recipientVerify only the requested address
PurposeSeparate login from password resetLogin codes cannot reset passwords
Verification valueCheck submitted contentStore a value computed with a server secret rather than plaintext
ExpirationReject expired codesExpire after 5 minutes
Attempt countLimit guessingInvalidate after 5 incorrect attempts
Used statusPrevent repeated loginInvalidate immediately after success

Six-digit codes have a limited search space. Rate-limit by email and request source in addition to limiting attempts per code. Ordinary digests are easy to brute-force after records leak, so include a server secret in the verification computation and manage it separately from records.


✅ Return results from the verification endpoint

The client submits an email, code, and the agreed purpose, for example to a login endpoint:

POST /auth/code-login HTTP/1.1
Content-Type: application/json

{"email":"reader@example.com","code":"123456"}

The server finds the record, checks purpose, expiration, and attempts, then verifies the value. On success, invalidate the code, create a login session, and return success. Otherwise return a generic “Invalid or expired verification code” without revealing whether the email is registered.

Checking and invalidating must happen together so concurrent requests cannot both succeed. Use a database transaction or atomic cache operation. If an authentication service provides code verification, call its sending and verification endpoints and let it manage this state.

The earlier script only delivers email. Production login also needs record persistence and consumption according to these rules.


🌐 Set timeouts for external HTTP requests

Use fixed server-approved addresses for third-party calls. This example calls the local health endpoint from the routing article so you can verify success and failure:

health-client.mjs
const response = await fetch('http://127.0.0.1:3000/health', {
    signal: AbortSignal.timeout(1000),
    redirect: 'error'
});
if (!response.ok) throw new Error('External API returned a failure');
const data = await response.json();
if (data.status !== 'ok') throw new Error('External response does not match the contract');
console.log(data.status);

Start routing-server.mjs, then run node health-client.mjs; expect ok. Requests fail after the service stops, and waiting is canceled if the call does not finish within one second. Never use arbitrary client-supplied URLs as server request targets.


🛑 Do not retry blindly after a timeout

A timeout only means no result arrived in time. The other service may already have sent email or created a record. For state-changing calls, use provider-supported request identifiers or idempotency so retries cannot duplicate the operation.

For Webhooks—third-party notifications to your endpoint—verify signatures according to the provider's protocol and record event IDs. Acknowledge an already processed notification without executing business logic again.


❓ Questions and Answers

Q1: Can successful submission be presented as guaranteed delivery?

No. Delivery results determine that. The page can say “Email submitted. Check your inbox.”

Q2: What happens to a verification code when sending fails?

Revoke the undelivered request or follow a consistent retry policy rather than generating valid records that continually overwrite one another.

Q3: Is comparing the code for equality enough?

Also check the recipient, purpose, expiration, attempt count, and whether it was used.


🧪 Practice

Verify that the local health request succeeds and fails after shutdown. Send email to your own test address and record the difference between service acceptance and actual receipt.

// Record your results here