fastify-auto-env-validator
v1.1.2
Published
A Fastify plugin for automatic detection and validation of environment variables in Node.js projects.
Maintainers
Readme
Fastify Auto Env Validator
Fastify Auto Env Validator is a Fastify plugin that automatically detects, validates, and manages required environment variables in your Node.js projects.
A Fastify plugin that automatically detects, validates, and ensures required environment variables are properly set in your project.
🚀 Features
- Automatic Environment Variable Detection: Scans your codebase to find
process.envusages. - Schema-Based Validation: Supports custom validation schemas for environment variables.
- Auto-Generate
.env.example: Keeps.env.exampleup-to-date with detected variables. - Fastify Plugin Support: Works seamlessly as a Fastify plugin.
📦 Installation
npm install fastify-auto-env-validatoror using Yarn:
yarn add fastify-auto-env-validator🚀 Usage
Basic Setup
import Fastify from "fastify";
import envValidator from "fastify-auto-env-validator";
const fastify = Fastify();
// With schema (recommended)
fastify.register(envValidator, {
schema: {
DATABASE_URL: { type: "string", required: true },
PORT: { type: "number", default: 3000 },
},
});
// Or without schema (auto-detects from code)
// fastify.register(envValidator);
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server running at ${address}`);
});Auto-Generate .env.example
If the .env.example file is missing, the plugin will create one based on detected environment variables.
⚙️ Options
| Option | Type | Description |
| ----------- | -------- | ------------------------------------------------------------------ |
| schema | Object | Custom schema to validate environment variables. |
| scanPaths | string[] | (Optional) Array of glob patterns to scan for process.env usage. |
✅ Validation Schema
Define a validation schema to enforce required variables:
const schema = {
DATABASE_URL: { type: "string", required: true },
API_KEY: { type: "string", required: true },
PORT: { type: "number", default: 3000 },
};type: for documentation only (not enforced by the plugin)required: if true, throws if missingdefault: value to use if not setvalidate: custom function(value) => true | stringfor custom validation
🛠 Development & Testing
Clone the repo and install dependencies:
git clone https://github.com/Dhanapandi555/fastify-auto-env-validator.git
cd fastify-auto-env-validator
npm installRun tests:
npm test📜 License
This project is licensed under the MIT License.
Made with ❤️ by Dhanapandi
