rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Start from the template. src/app.service.ts stays as it is.

Install#

Shell
bun add nodemailer
bun add -d @types/nodemailer

The transport is created at startup#

A transport holds connection settings, so it is built once at startup by a small module, handed to the app through its startup context, and closed on shutdown by the register cleanup (it runs on app.stop()). Without SMTP_HOST, the JSON transport builds each message and returns it instead of sending, so the app runs and tests with no mail server. The module exports the mailer the app uses; the transport stays in the module's own context, and the app picks only what it needs.

TypeScript
// src/mail/mail.ts
import { Rhythm, decorate } from "@rhythmjs/rhythm";
import nodemailer from "nodemailer";

function createTransport() {
  return process.env.SMTP_HOST
    ? nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT ?? 1025),
        auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
      })
    : nodemailer.createTransport({ jsonTransport: true });
}

function createMailer(transport: ReturnType<typeof createTransport>) {
  return {
    sendWelcome: (to: string, name: string) =>
      transport.sendMail({
        from: "RhythmJS <hello@example.com>",
        to,
        subject: `Welcome, ${name}`,
        text: `Hi ${name}, thanks for signing up.`,
      }),
  };
}

export type Mailer = ReturnType<typeof createMailer>;

export const mailModule = new Rhythm({ name: "mail" }).register(
  decorate(() => {
    const transport = createTransport();
    return { transport, mailer: createMailer(transport) };
  }),
  ({ transport }) => transport.close(),
);

The controller sends mail#

The template's controller gets mailer in its context type and a POST /signup route.

TypeScript
// src/app.controller.ts
import { RhythmRouter } from "@rhythmjs/router";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import type { appService } from "./app.service";
import type { Mailer } from "./mail/mail";
import { error, json, text } from "@rhythmjs/router/response";

export type AppContext = RhythmHttpContext & {
  appService: typeof appService;
  mailer: Mailer;
};

export const appController = new RhythmRouter<AppContext>()
  .get("/", (ctx) => {
    text(ctx, ctx.appService.getHello());
  })
  .post("/signup", async (ctx) => {
    const { name, email } = (await ctx.request.json()) as { name?: string; email?: string };
    if (!name || !email?.includes("@")) {
      error(ctx, 400, "name and a valid email are required");
      return;
    }

    const info = await ctx.mailer.sendWelcome(email, name);
    json(ctx, { messageId: info.messageId }, 201);
  });

Include it in the app#

The app module includes the mail module, picking mailer, and mounts the controller. main.ts stops the app on SIGINT, which closes the transport.

TypeScript
// src/app.module.ts
import { Rhythm, decorate, include, mount } from "@rhythmjs/rhythm";
import { appController } from "./app.controller";
import { appService } from "./app.service";
import { mailModule } from "./mail/mail";

export const appModule = new Rhythm({ name: "app" })
  .register(include(mailModule, ({ mailer }) => ({ mailer })))
  .register(decorate(() => ({ appService })))
  .use(mount(appController));
TypeScript
// src/main.ts
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { appModule } from "./app.module";

const port = Number(process.env.PORT ?? 3009);

const server = Bun.serve({ port, fetch: toFetchHandler(appModule) });
console.log(`listening on ${server.url}`);

process.on("SIGINT", async () => {
  await server.stop();
  await appModule.stop();
  process.exit(0);
});

Things to check#

  • A slow SMTP server slows the response. If the mail is not part of the answer, start the send without awaiting it and log failures; note that nothing retries it.
  • Never build from or to from unchecked input.
  • For a real inbox locally, run Mailpit and set SMTP_HOST=localhost.

The full app, with tests, is examples/nodemailer, built from the template.