--- title: "Providers" description: "Install Beignet provider adapters for databases, caches, mail, auth, logging, jobs, rate limits, and event buses." url: "https://www.beignetjs.com/providers" markdown_url: "https://www.beignetjs.com/markdown/providers.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Providers Providers are startup-time adapters. They install concrete ports for databases, caches, storage, mail, payments, feature flags, auth, logging, jobs, rate limits, and other external services while handlers and use cases depend only on `ctx.ports`. Read [Ports and adapters](https://www.beignetjs.com/markdown/ports.md) first if you want the dependency boundary. Read the production feature pages when you want a task-specific guide, and [Writing a provider](https://www.beignetjs.com/markdown/writing-a-provider.md) when you are building a reusable provider package. ## How providers fit Start from the [Quickstart](https://www.beignetjs.com/markdown/getting-started.md) app's existing provider registry. It already installs authentication, logging, the database, and app repositories. Add a capability by extending that registry and the matching port wiring. Provider-installed ports are available in context factories, route handlers, hooks, use cases, and `server.ports`. Generated apps keep provider wiring in two places: - `infra/port-wiring.ts` binds app-owned ports such as the policy gate and declares the rest as deferred provider-contributed keys with `definePorts()({ bound, deferred })`. - `server/providers.ts` registers runtime providers in startup order, exported `as const` so port types can be inferred from the list. App-owned infra providers, such as a database provider that wires repositories, belong under `infra/` and are registered from `server/providers.ts` after the provider that installs the lower-level port they need. For common first-party production providers, let the CLI apply the wiring: ```bash bun beignet provider add mail-resend bun beignet provider add search-meilisearch bun beignet provider add cache-redis bun beignet provider add event-bus-redis bun beignet provider add storage-s3 ``` Each preset updates dependencies, `server/providers.ts`, `AppPorts`, `infra/port-wiring.ts`, `.env.example`, and `docs/providers.md`. Use `--dry-run --json` to review the changes before writing. After applying a preset, run your package manager's install command and configure its environment variables. Verify with `beignet provider audit` and `beignet doctor --strict`. Choose one provider per app-facing port: for example, use `mail-resend` or `mail-smtp`, not both. After all providers have started, the server verifies that every deferred port was contributed and fails boot with the missing keys otherwise. See [Defer ports to providers](https://www.beignetjs.com/markdown/ports.md#defer-ports-to-providers) for the `onUnboundPorts` options. ## Typed provider ports `InferProviderPorts` extracts and merges the ports a provider list contributes, so app code can type `ctx.ports` without hand-written casts: ```typescript // app-context.ts (port types excerpt) import type { InferProviderPorts } from "@beignet/core/providers"; import type { AppPorts } from "@/ports"; import type { providers } from "@/server/providers"; export type AppRuntimePorts = AppPorts & InferProviderPorts; ``` Use `AppRuntimePorts` for the existing `AppContext.ports` field and preserve the context's identity and request fields. The import of `providers` is type-only, so `app-context.ts` stays free of runtime server dependencies. App-local providers can declare the ports they require from earlier providers, plus their app context and service-context input, through the curried `createProvider()` form: ```typescript import { createProvider } from "@beignet/core/providers"; import type { DbPort } from "@beignet/provider-db-drizzle/sqlite"; import type { AppContext } from "@/app-context"; import type { AppServiceContextInput } from "@/server"; import type { AppPorts } from "@/ports"; import type * as schema from "./schema"; export const appDatabaseProvider = createProvider< { db: DbPort }, AppContext, AppServiceContextInput >()({ name: "app-database", async setup({ ports }) { const providedPorts: Pick = { ...createRepositories(ports.db.drizzle), uow: createUnitOfWork(ports.db.drizzle), }; return { ports: providedPorts }; }, }); ``` Annotate the returned ports with a `Pick` of the keys the provider fulfills. [Writing a provider](https://www.beignetjs.com/markdown/writing-a-provider.md) covers the typing guidance for setup results and lifecycle hooks in detail. ## Naming conventions Provider exports follow a small naming rule: ```typescript // Provider factories with env-backed defaults need no options createRedisCacheProvider() createPinoLoggerProvider() createSmtpMailProvider() // Provider factories accept app-owned runtime input and return a provider createDrizzleSqliteProvider({ schema }) createBetterAuthProvider({ auth }) createMemoryEventBusProvider() // Direct port factories return concrete implementations for manual wiring createMemoryEventBus() createMemoryMailer() createRedisCache({ client }) createPinoLogger({ logger }) createUpstashRateLimit({ client }) createBetterAuthPort({ auth }) ``` Use `createXProvider(...)` for Beignet lifecycle providers registered with `providers: []`. Provider packages expose factories rather than shared singleton instances, so each server composition owns its provider object. Use `createXPort()` or a domain-specific factory name for direct implementations assigned under `ports`. Webhook verifier packages are server integrations, not providers. They do not install ports or appear in provider audits. They adapt vendor signature rules to `@beignet/core/webhooks` and are passed at the route/server boundary, usually through `createWebhookRoute(...)`. When a vendor also has a full app-facing port, prefer that capability provider for that workflow; for example Stripe billing uses `@beignet/provider-payments-stripe` and `createPaymentWebhookRoute(...)`, while `@beignet/webhooks-stripe` is for generic Stripe inbound events. ## Provider vs port factory A port factory is just app code that returns one concrete port. It is the right shape for simple dependencies, tests, and one-off adapters. ```typescript import { createMemoryMailer } from "@beignet/core/mail"; import { definePorts } from "@beignet/core/ports"; export const initialPorts = definePorts({ logger: fallbackLogger, mailer: createMemoryMailer(), }); ``` A provider participates in server startup. Use one when infrastructure needs configuration loading, setup order, startup checks, teardown, provider instrumentation, or reusable packaging. For example, `bun beignet provider add mail-smtp` adds the mail provider to `server/providers.ts` and defers its port in `infra/port-wiring.ts`. The existing `server/index.ts` consumes that registry without replacement. ## Setup order Providers run in the order you pass them to the server. Each provider sees base ports plus ports returned by earlier providers. In the default SQLite starter, `drizzleSqliteProvider` installs the database before `starterDatabaseProvider` binds repositories and Unit of Work: ```typescript // server/providers.ts (provider list excerpt) export const providers = [ createDevtoolsProvider(), createBetterAuthProvider({ auth }), createPinoLoggerProvider(), drizzleSqliteProvider, starterDatabaseProvider, ] as const; ``` These imports and provider instances already exist in the starter file. Add new entries to your current list, preserving the providers that fulfill its deferred ports. When two providers return the same port key, the later provider wins. Use that deliberately for environment-specific overrides. ## Lifecycle `setup` runs during server creation. `start` runs after all providers have contributed ports. `stop` runs when the server is stopped. Provider lifecycle hooks should do bounded resource work: create clients, install ports, run startup checks, and close resources. Do not start polling loops, queue consumers, or other unbounded background work from `setup` or `start` in serverless apps. Put background work behind explicit runtime entrypoints such as cron routes, scheduled handlers, job functions, or worker processes. See [Runtime recipes](https://www.beignetjs.com/markdown/runtime-recipes.md) for the process layouts and readiness checks those entrypoints should use. ```typescript import { createProvider } from "@beignet/core/providers"; import { z } from "zod"; const CacheConfigSchema = z.object({ URL: z.string().url(), }); export const cacheProvider = createProvider({ name: "cache", config: { schema: CacheConfigSchema, envPrefix: "CACHE_" }, async setup({ config }) { const client = await connectToCache(config.URL); return { ports: { cache: { get: (key) => client.get(key), set: async (key, value, options) => { if (options?.ttlSeconds) { await client.set(key, value, { ttlSeconds: options.ttlSeconds }); } else { await client.set(key, value); } }, delete: async (key) => client.delete(key), has: async (key) => (await client.exists(key)) > 0, remember: async (key, factory, options) => { const cached = await client.get(key); if (cached != null) return cached; const value = await factory(); await client.set(key, value, options?.ttlSeconds); return value; }, }, }, async stop() { await client.close(); }, }; }, }); ``` The `envPrefix` strips the prefix before validation. For example, `CACHE_URL=redis://localhost:6379` becomes `{ URL: "redis://localhost:6379" }`. ## Escape hatches First-party providers expose stable app-facing ports for normal use and raw clients as escape hatches for provider-specific features. ```typescript await ctx.ports.mailer.send({ to: "user@example.com", subject: "Welcome", text: "Hello", }); await ctx.ports.resend.client.emails.send({ from: "sender@example.com", to: "user@example.com", subject: "Invoice", html: "

Your invoice is ready.

", tags: [{ name: "category", value: "invoice" }], }); ``` Application code should prefer the stable port. Use the escape hatch only when the provider has a feature the port intentionally does not model. Each capability page lists the escape-hatch port its providers install. ## First-party providers Provider packages are named `provider--`. When an implementation spans multiple database backends, each backend is a subpath export: the Drizzle package ships `@beignet/provider-db-drizzle/sqlite`, `/postgres`, and `/mysql`, with database drivers as optional peer dependencies so apps install only the driver they use. | Concern | Package | Installs | Read next | | --------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- | | Database | `@beignet/provider-db-drizzle` | `db` plus per-backend Drizzle helpers via `/sqlite`, `/postgres`, and `/mysql` | [Database and transactions](https://www.beignetjs.com/markdown/database.md) | | Cache | `@beignet/provider-cache-redis` | `cache`, plus `redis` escape hatch | [Cache](https://www.beignetjs.com/markdown/cache.md) | | Search | `@beignet/provider-search-meilisearch` | `search`, plus `meilisearch` escape hatch | [Search](https://www.beignetjs.com/markdown/search.md) | | Storage | `@beignet/provider-storage-local`, `@beignet/provider-storage-s3`, `@beignet/provider-storage-vercel-blob` | `storage`, plus `s3Storage`/`vercelBlob` provider escape hatches | [Storage](https://www.beignetjs.com/markdown/storage.md) | | Mail | `@beignet/provider-mail-resend`, `@beignet/provider-mail-smtp` | `mailer`, plus `resend` or `smtp` escape hatch | [Mail](https://www.beignetjs.com/markdown/mail.md) | | Web Push | `@beignet/provider-push-web` | `webPush` | [Notifications](https://www.beignetjs.com/markdown/notifications.md#web-push) | | Payments | `@beignet/provider-payments-stripe` | `payments`, plus `stripe` escape hatch | [Payments and billing](https://www.beignetjs.com/markdown/payments.md) | | Feature flags | `@beignet/provider-flags-openfeature` | `flags`, plus `openFeature` escape hatch | [Feature flags](https://www.beignetjs.com/markdown/feature-flags.md) | | Error reporting | `@beignet/provider-error-reporting-sentry` | `errorReporter`, plus `sentry` escape hatch | [Error reporting](https://www.beignetjs.com/markdown/error-reporting.md) | | Locks | `@beignet/provider-locks-redis` | `locks`, plus `redisLocks` escape hatch | [Locks and leases](https://www.beignetjs.com/markdown/locks.md) | | Logger | `@beignet/provider-logger-pino` | `logger` | [Logging](https://www.beignetjs.com/markdown/logging.md) | | Rate limiting | `@beignet/provider-rate-limit-upstash` | `rateLimit`, plus `upstash` escape hatch | [Rate limiting](https://www.beignetjs.com/markdown/rate-limiting.md) | | Event bus | `@beignet/provider-event-bus-memory`, `@beignet/provider-event-bus-redis` | `eventBus`, plus `redisEventBus` escape hatch for Redis | [Events](https://www.beignetjs.com/markdown/events.md) | | Auth | `@beignet/provider-auth-better-auth` | `auth` | [Authentication](https://www.beignetjs.com/markdown/authentication.md) | | Jobs | `@beignet/provider-jobs-bullmq`, `@beignet/provider-jobs-inngest` | `jobs`, plus `bullMQJobs` or `inngest` escape hatch | [Jobs](https://www.beignetjs.com/markdown/jobs.md) | Webhook signature integrations are listed separately because they do not install lifecycle providers or ports: use `@beignet/webhooks-github` for GitHub deliveries and `@beignet/webhooks-stripe` for generic Stripe events. See [Webhooks](https://www.beignetjs.com/markdown/webhooks.md). ## Provider packages Reusable provider packages carry conventions beyond the runtime object: a static `beignet.provider` metadata manifest in `package.json` that `beignet doctor` reads, provider instrumentation so external work appears in devtools, and explicit durable-workflow semantics for providers that participate in jobs, events, schedules, or outbox delivery. Run `beignet provider audit` for a report-only inventory of installed provider metadata, registration, env, tables, and app ports; JSON output also includes active variants and watchers. Run `beignet provider add ` when you want the CLI to install and wire one of the stable presets (`flags-openfeature`, `mail-resend`, `mail-smtp`, `push-web`, `search-meilisearch`, `error-reporting-sentry`, `rate-limit-upstash`, `cache-redis`, `event-bus-redis`, `locks-redis`, `storage-s3`, or `storage-vercel-blob`) instead of copying the setup recipe by hand. Check a provider's README for environment variables, installed ports, failure behavior, and deployment requirements. Retry behavior varies by provider: mail providers report send failures without retrying, leaving retries to jobs or the outbox because sends are not idempotent; the S3 provider delegates bounded transient retries to the AWS SDK. Providers with cheap, non-mutating dependency probes expose explicit `checkHealth()` helpers on their provider-owned ports or escape hatches for app-owned `/api/ready` routes. [Writing a provider](https://www.beignetjs.com/markdown/writing-a-provider.md) covers all of these. ## Process boundaries of memory providers Memory ports — cache, rate limit, locks, search, event bus, payments — keep their state in the process that created them. A seed script and a dev server are different processes, so state written by one is invisible to the other: documents a seed script indexes into `createMemorySearchProvider()` do not exist in the dev server's search port, and cache entries or rate-limit counters written in one process never appear in another. When a workflow depends on derived state such as a search index: - Rebuild the derived state inside the serving process. Run a boot or backfill [task](https://www.beignetjs.com/markdown/tasks.md) against the server's own ports — for example an `issues.backfill-search` task that re-indexes every issue — or keep the state current with sync listeners driven by the [outbox](https://www.beignetjs.com/markdown/outbox.md). - Swap the memory provider for a shared-store provider in the provider list: `@beignet/provider-search-meilisearch` for search, `@beignet/provider-locks-redis` for locks, or `@beignet/provider-rate-limit-upstash` for rate limits. Every process then reads and writes the same store. - Never treat a memory provider as a fixture that a separate process can preload. If a script must prepare state for the server, that state has to live in a shared store the server also reads. ## Testing For tests, pass mock or memory ports directly instead of booting production providers: ```typescript const testPorts = definePorts({ posts: createInMemoryPostRepository(), mailer: createMemoryMailer(), logger: { info: () => {}, error: () => {}, }, }); ``` Handlers and use cases still receive `ctx.ports`, so production and test code paths stay the same. ## Broadcasting providers `@beignet/provider-broadcast-memory` and `@beignet/provider-broadcast-redis` implement `BroadcastPort` from `@beignet/core/broadcasting/server`. Select them with `beignet provider add broadcast-memory` or `broadcast-redis`. Memory is limited to one process. Redis connects request replicas and workers; configure `REDIS_BROADCAST_URL` and a prefix unique to the application and environment. Run `bun install` after selecting a provider. When switching implementations, replace the existing broadcast provider registration so only one fills the port. Both transports are ephemeral and require browser refetch after reconnection. See [Broadcasting](https://www.beignetjs.com/markdown/broadcasting.md) for authorized streams and deployment limits.