This bug made it into the released versions of my Next.js 15 templates (two booking sites, a barbershop and a dental clinic, and two small online stores). All the tests were green. The booking flow had a row lock, an idempotency key and a race test. And it could still book the same customer twice.

Here's the flow it broke:

  1. The customer submits the form.
  2. The appointment is committed to Postgres.
  3. The route sends a confirmation email with Nodemailer.
  4. The route returns the link to the appointment page.

Step 3 is the problem. If the SMTP server is down, slow, or rejects the login, sendMail throws. The appointment is already saved, but the route returns a 500 and the customer sees "Something went wrong."

What does a normal person do after "Something went wrong"? Pressing the button again would actually have been safe, because the form reuses its idempotency key. But a lot of people reload and try again. The reloaded form has a new idempotency key, so the server sees a brand new request. Their own time now shows as taken, so they pick another one and end up with two appointments.

There were two more side effects:

  • The owner alert ("New online booking") was sent after the customer email, so it was skipped too. The shop had a booking in the admin panel that the owner was never told about.
  • In the stores, the email goes out after payment, inside markPaid(). In the Stripe webhook, the order was marked paid and then the email threw. The webhook returned 500, so Stripe retried. The retry found the order already paid and returned early, so the receipt never went out (and neither did the owner's "New order" alert), and every paid order left a failed delivery in the Stripe dashboard.

And a smaller, more embarrassing one: the pages claimed an email had gone out no matter what. The dental template's appointment page said "we sent the details to your email," and the bakery's order page said "We sent a confirmation to your email," even when SMTP_URL wasn't configured at all.

How I found it

Not from a user report. I was doing a bug-hunting pass over the templates, going through each external dependency and asking "what happens if this is down?" For email, the cheapest way to test that is to point SMTP_URL at a port where nothing listens:

SMTP_URL=smtp://127.0.0.1:1 

Then book an appointment. The booking showed up in the admin panel, and the booking form showed an error. That was enough.

My tests never caught it, because in tests sendMail just pushed messages into an array. It could never fail.

Fix 1: sendMail never throws

The rule I settled on: sending an email is a side effect, not part of the transaction, so its failure is a value, not an exception.

/** Send one email. Never throws: a transport failure (SMTP down, bad credentials, rejected address) is logged and reported as `false`. */ export async function sendMail(to: string, subject: string, text: string): Promise<boolean> { try { // ...test mode / no transport handling... await t.sendMail({ from, to, subject, text }); return true; } catch (err) { // only the error message: no recipient, body or connection string (it can contain the SMTP password) console.error(`[mail] could not send "${subject}": ${err instanceof Error ? err.message : "unknown error"}`); return false; } } 

Two details I care about here. First, the log line has the subject and the error message, nothing else. Logging the whole error object can print the transport config, and an SMTP URL often has the password in it. The recipient's address and the email body don't belong in logs either.

Second, when SMTP isn't configured, sendMail returns false instead of pretending. In production it also warns that the email was not sent. That return value is what the UI uses later.

Fix 2: an explicit "after commit" step

Making sendMail safe isn't enough on its own. After the insert there's still other code: a lookup of the barber's name, formatting the date, the owner alert. Any of that can throw too.

So in book(), everything after the transaction runs in its own try/catch:

if (!res.created) return { ...res, emailSent: false }; // emails go out only for a newly created appointment const appt = res.appt; try { return { appt, created: true, emailSent: await afterBooking(db, appt, svc!.name) }; } catch (err) { // the appointment is already saved: a failure here must not turn the booking into an error page console.error(`[book] appointment #${appt.id} saved, but the follow-up failed: ${err instanceof Error ? err.message : "unknown error"}`); return { appt, created: true, emailSent: false }; } 

Once the row is committed, the request has succeeded. Nothing after that line is allowed to change the answer. Writing it as a separate step makes that boundary visible in the code, which helps the next person (usually me) not to put something important after it.

The Stripe webhook got the same treatment in markPaid(): after the conditional UPDATE ... SET status = 'paid', the follow-up runs in a try/catch and the webhook returns 200. Stripe only needs to know that we recorded the payment. Whether the receipt email went out is our problem, not something to retry the whole event for.

Fix 3: the owner hears about it

afterBooking() sends the client's email first and passes the result into the owner alert:

const emailSent = await sendMail(appt.email, `Your chair at ${site} is booked`, body); await notifyOwners(db, "New online booking", `${serviceName} with ${who?.name}\n${when}` + (emailSent ? "" : "\nThe confirmation email to the client was not sent (no SMTP or a sending error); they have their booking link on screen.")); return emailSent; 

If SMTP is completely down, this alert fails too, of course. But a common case is a rejected or mistyped customer address, and then the owner gets a clear note and can call or text the client.

Fix 4: the page only claims what really happened

The route passes the result to the appointment page through the URL:

const { appt, emailSent } = await book(db, input); // "emailed=1" only when the confirmation email really went out return publicJson(200, { url: `/appointment/${appt.publicId}?booked=1${emailSent ? "&emailed=1" : ""}` }); 

And the page picks its message:

const emailNote = booked && a.status === "booked" ? (mailConfigured() && emailed === "1" ? " We sent the details to your email." : " Save this page — it's your booking link.") : ""; 

The appointment page itself is the confirmation. It has a random 128-bit ID, it shows the time, the barber and a cancel button. So when the email didn't go out, the honest message is "save this page," and the customer still has everything they need. Someone could add &emailed=1 by hand, but that only changes a sentence on their own page.

The test that would have caught it

The test transport now has a switch that makes the next sends fail:

/** tests only: the next `n` sends fail as if the SMTP server were down */ export const failNextMail = (n = 1) => { failNext = n; }; 

And the test checks what actually matters: the booking is saved, the result is honest, and the owner is still told.

it("a broken SMTP server does not fail a booking", async () => { await addUser(db, "owner@x.com", "owner"); const before = sentMail().length; failNextMail(1); // the client's confirmation email fails const r = await book(db, input(), NOW); expect(r.created).toBe(true); expect(r.emailSent).toBe(false); expect(await db.select().from(appointments)).toHaveLength(1); const alerts = sentMail().slice(before); expect(alerts[0]!.text).toMatch(/confirmation email to the client was not sent/); }); 

A second test goes through the real route handler with failNextMail(1) and checks that the response is 200 and the URL ends in ?booked=1 without &emailed=1.

What I didn't do (and why)

The "proper" fix is an outbox: in the same transaction as the booking, insert a row into an outbox table, and let a background worker send the email and retry until it succeeds. A queue (BullMQ, SQS, a hosted job service) is a variation of the same idea. You get retries and you never lose an email.

For a barbershop or a small bakery on Vercel, that means a worker or a cron job, a retry policy, and one more thing the owner has to keep running. A shop like that gets maybe a few dozen bookings a day. If an email fails, the customer already has the booking page on screen, and the owner gets a note. I think that trade-off is fine here. If a project needed guaranteed delivery (invoices, legal notices), I'd go with the outbox.

The main lesson for me: once the commit has happened, the request has succeeded. Everything after it is best effort and has to be written that way.

The demo is here: https://iron-lantern-barber.vercel.app

The code from this post is in the barbershop template, and the same fix is in all of them in the Next.js templates bundle.

How do you handle side effects after a commit in your apps: inline best effort like this, an outbox table, or a queue from day one?