Skip to content

Latest commit

 

History

History
114 lines (86 loc) · 3.61 KB

README.md

File metadata and controls

114 lines (86 loc) · 3.61 KB

@yolk-oss/elysia-env

elysia npm version npm downloads bundle License

A plugin for Elysia.js to validate environment variables and inject them into your application.

Table of Contents

Installation

To install @yolk-oss/elysia-env with Bun, run the following command:

bun add @yolk-oss/elysia-env

Basic Usage

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.

Features

Custome Environment Sources

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',
    },
})

Error Handling

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
})

Success Callback

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)
    },
})

License

MIT