A plugin for Elysia.js to validate environment variables and inject them into your application.
To install @yolk-oss/elysia-env
with Bun, run the following command:
bun add @yolk-oss/elysia-env
The @yolk-oss/elysia-env
plugin provides a way to validate and inject environment variables into your Elysia.js application.
You define a schema for the environment variables using TypeBox, and the plugin will validate them, inject them, and handle errors based on your preferences.
import { Elysia, t } from 'elysia'
import { env } from '@yolk-oss/elysia-env'
const app = new Elysia()
.use(
env({
TOKEN: t.String({
minLength: 5,
error: 'TOKEN is required for a service!',
}),
}),
)
.get('/', ({ env }) => env.TOKEN)
// ^? (property) TOKEN: string
.listen(8080)
console.log(`Listening on http://${app.server!.hostname}:${app.server!.port}`)
Checkout the examples and tests folders on github.
You can specify a custom source for the environment variables. By default, the plugin uses process.env, but you can use alternative sources like secret managers, custom storage, etc.
env(schema, {
envSource: {
API_KEY: 'custom-api-key',
DB_URL: 'custom-db-url',
},
})
You can control how the plugin handles validation errors through the onError
option:
- 'exit': Exits the process with an error code 1 (default).
- 'warn': Logs a warning message but continues running the app.
- 'silent': Continues without logging anything.
- Function: You can pass a custom error handler function.
env(schema, {
onError: 'warn', // Logs a warning and continues
})
You can define a callback function that is executed when the environment variables pass validation successfully.
env(schema, {
onSuccess: (env) => {
console.log('Successfully loaded environment variables:', env)
},
})