@fastify/env
Loads and validates environment variables against a JSON Schema.
Syntax
app.register(fastifyEnv, { schema, dotenv? }) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
options | object | No | schema for required env vars, plus dotenv and confKey options. |
Returns
Promise<void> — Resolves after validation, rejecting on failure.
Throws
Error— Rejected at boot when a required variable is missing or invalid.
Examples
import Fastify from 'fastify';
import fastifyEnv from '@fastify/env';
const app = Fastify();
await app.register(fastifyEnv, {
dotenv: true,
schema: {
type: 'object',
required: ['PORT', 'DATABASE_URL'],
properties: {
PORT: { type: 'number', default: 3000 },
DATABASE_URL: { type: 'string' },
},
},
});
app.get('/cfg', async () => ({ port: app.config.PORT }));
Notes
Validated values are exposed on app.config (configurable via confKey).
The app fails fast at boot if required variables are missing, surfacing
misconfiguration early.