{"id":23002505,"url":"https://github.com/mujeebdev3/typesafe-env","last_synced_at":"2025-08-14T01:31:19.762Z","repository":{"id":264256021,"uuid":"892848515","full_name":"mujeebdev3/typesafe-env","owner":"mujeebdev3","description":"Ts-TypeSafeEnv: A lightweight TypeScript library for managing type-safe environment variables. Say goodbye to runtime errors with compile-time validation and effortless setup—perfect for building reliable, error-free JavaScript or TypeScript projects 🚀.","archived":false,"fork":false,"pushed_at":"2024-12-11T16:33:23.000Z","size":84,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-09T17:55:31.491Z","etag":null,"topics":["dotenv","environment-variables","nodejs-tools","npm","runtime-safety","trustyourenvvars","ts-typesafe-env","type-safety","typesafe-config","typesafeenv","typescript","zeroriskenvvars"],"latest_commit_sha":null,"homepage":"https://mujeebdev3.github.io/typesafe-env/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mujeebdev3.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.MD","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-22T22:34:16.000Z","updated_at":"2025-07-28T12:01:41.000Z","dependencies_parsed_at":"2024-11-22T23:25:12.041Z","dependency_job_id":"f7509e47-57e2-4a1d-b1fe-1c5eb4fff1e6","html_url":"https://github.com/mujeebdev3/typesafe-env","commit_stats":null,"previous_names":["innocent6303/typesafe-env","mujeebdev3/typesafe-env"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/mujeebdev3/typesafe-env","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mujeebdev3%2Ftypesafe-env","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mujeebdev3%2Ftypesafe-env/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mujeebdev3%2Ftypesafe-env/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mujeebdev3%2Ftypesafe-env/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mujeebdev3","download_url":"https://codeload.github.com/mujeebdev3/typesafe-env/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mujeebdev3%2Ftypesafe-env/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270347431,"owners_count":24568569,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-13T02:00:09.904Z","response_time":66,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotenv","environment-variables","nodejs-tools","npm","runtime-safety","trustyourenvvars","ts-typesafe-env","type-safety","typesafe-config","typesafeenv","typescript","zeroriskenvvars"],"created_at":"2024-12-15T07:11:14.866Z","updated_at":"2025-08-14T01:31:19.508Z","avatar_url":"https://github.com/mujeebdev3.png","language":"TypeScript","readme":"# **🌟 Ts-Typesafeenv** - Safe and Efficient Environment Variable Validation\n\n![npm](https://img.shields.io/npm/v/ts-typesafe-env?style=flat-square) ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)\n\n## **💡 Introduction**\n\nEnvironment variables are crucial for managing configuration and sensitive data in modern applications. While `.env` files are useful, managing a growing list of variables in large projects can be challenging.\n\n**Ts-Typesafeenvv** ensures your environment variables are **defined** and **validated** in a consistent, reliable way, reducing the risk of runtime errors.\n\n---\n\n## **🚀 Why Ts-Typesafeenv?**\n\nStruggling with managing environment variables? Here's why **Ts-Typesafeenv** is your go-to solution:\n\n✅ **Predefined Validation**: Validate with `getString`, `getNumber`, and `getBoolean`.  \n✅ **Environment-Specific Config**: Handle different environments (production, development) effortlessly.  \n✅ **Built-In Functions**: Quickly validate, list, and load variables with tools like `validateEnvironment`.  \n✅ **CLI Support**: Manage environment variables right from the terminal.  \n✅ **No Direct `process.env` Access**: Simplify access with intuitive methods.  \n✅ **Flexible File Loading**: Load variables from specific `.env` files for added flexibility.\n\n---\n\n## **✨ Features**\n\n```typescript\n- **`TypeSafeEnv.getString(key: string)`**: Validates and retrieves a string variable.\n- **`TypeSafeEnv.getNumber(key: string)`**: Ensures a number type and validates its presence.\n- **`TypeSafeEnv.getBoolean(key: string)`**: Confirms a boolean value (`true` or `false`).\n- **`TypeSafeEnv.loadFromFile(filePath: string)`**: Load environment variables from a specified `.env` file safely.\n- **`TypeSafeEnv.getEnvSpecificConfig(key: string, type: string)`**: Fetch environment-specific values for flexible configurations.\n- **`validateEnvironment(requiredVars: string[])`**: Validates multiple variables to prevent runtime errors.\n- **`listEnvironmentVariables()`**: Lists all loaded environment variables.\n```\n\n---\n\n## **📦 Installation**\n\nInstall Ts-Typesafeenv using **npm**:\n\n```bash\nnpm install ts-typesafe-env\n```\n\nOr with **yarn**:\n\n```bash\nyarn add ts-typesafe-env\n```\n\n---\n\n### ⚡ Usage\n\n// Importing the Package\n\nAfter installing the package, you can easily import it into your codebase using [`CommonJS`](#commonjs)?\n\n```typescript\nconst { TypeSafeEnv } = require(\"ts-typesafe-env\");\n```\n\n.. or Using[`ES6`](#ES6)?\n\n```javascript\nimport { TypeSafeEnv } from \"ts-typesafe-env\";\n```\n\n# Validating Environment Variables\n\n#### ✅ Use the **predefined methods** to validate your environment variables efficiently and reliably.\n\n### Example: Checking for a String Value\n\n```typescript\nconst dbUrl = TypeSafeEnv.getString(\"DB_URL\");\nconsole.log(dbUrl); // Your DB URL or an error if missing.\n```\n\n#### Example: Checking for a Number Value\n\n```typescript\nconst port = TypeSafeEnv.getNumber(\"PORT\");\nconsole.log(port); // The port number or an error if invalid.\n```\n\n#### Example: Checking for a Boolean Value\n\n```typescript\nconst isProd = TypeSafeEnv.getBoolean(\"IS_PROD\");\nconsole.log(isProd); // true/false or an error if invalid.\n```\n\n#### Managing Environment-Specific Configurations\n\n```typescript\nconst apiEndpoint = TypeSafeEnv.getEnvSpecificConfig(\n  \"API_URL\",\n  process.env.NODE_ENV || \"production\"\n);\nconsole.log(apiEndpoint);\n```\n\n\u003e This method ensures that the correct **environment variable** is used based on the **active environment**  \n\u003e _(i.e., `production` or `development`)_.\n\n#\n\n### Validating Multiple Environment Variables\n\n```javascript\nimport { validateEnvironment } from \"ts-typesafe-env\";\n\nTypeSafeEnv.validateEnvironment([\"DB_URL\", \"API_KEY\", \"NEW_DB\"]); //if any of the required variables are missing or invalid, the function will log an error to the console.\n```\n\n---\n\n### 🚀 No More `process.env`\n\nOne of the biggest **benefits** of `TypeSafeEnv` is that you don’t have to manually access each environment variable using `process.env.xyz`.\n\n\u003e Instead, you can simply call the appropriate method for each type of variable, ensuring you get the value you need in a **reliable** and **consistent** way.\n\n### 💡 Simplify Your Code with Typesafeenv\n\nFor example, instead of doing:\n\n```javascript\nconst dbUrl = process.env.DB_URL;\nif (!dbUrl) {\n  throw new Error(\"DB_URL is missing\");\n}\n```\n\nYou can simply use:\n\n```typescript\nconst dbUrl = TypeSafeEnv.getString(\"DB_URL\");\n```\n\n⚡ This eliminates the need for manual error handling and simplifies your code.\nSay goodbye to repetitive checks and write cleaner, more reliable code with TypeSafeEnv!\n\n## 🛠️ Command-Line Interface (CLI)\n\nWe also provide a **command-line interface (CLI)** to help you validate environment variables easily from the terminal.\n\n#### 📋 Features:\n\n- **Listing Environment Variables:**  \n  Quickly list all the environment variables loaded from your `.env` file for easy inspection.\n\n- **Validation Made Easy:**  \n  Use the CLI to validate your required environment variables effortlessly, reducing the risk of configuration issues.\n\n\u003e _This eliminates the need for manual error handling and simplifies the code._  \n\u003e _No more worrying about missing or misconfigured variables!_\n\n## **⚙️ CLI Tool**\n\n### List All Environment Variables\n\n```bash\nnpx typesafeenv list\n```\n\n```typescript\n# Expected Output:\nDB_URL=http://example.com\nAPI_KEY=your-api-key\nCondition=true\nNEW_DB=Tested Database\nDB_SESSION=my-session\nDB_URL_development=localhost/dev_db\nDB_URL_production=localhost/dev_PR\n```\n\n---\n\nThis command displays the current values of all environment variables accessible in your project. It allows you to verify that each variable is properly defined in your .env file or other configuration sources..\n\n---\n\n### List Environment Variables Using a Keyword\n\n```bash\nnpx typesafeenv list \"API_KEY\"\n```\n\n```typescript\n# Expected Output:\nAPI_KEY=your-api-key\n```\n\n### List Environment Variables from Another File with a Keyword and Path\n\n\u003e Note: You can also provide a specific keyword for the search, and the result will display only the relevant variables.\n\n```typescript\nExample:\nnpx typesafeenv list \"max_size\" \"./config/.env\"\nOutput:max_size=12\n```\n\n```typescript\nnpx typesafeenv list \"\" \"./config/.env\"\n# Expected Output:\nNEW_DB_NAME=New Tested Database\nDB_URL_NEW=https://localhost\nmax_size=12\nDB_SESSION_NEW=true\n```\n\n### Validate Environment Variables\n\n```bash\nnpx typesafeenv validate -v DB_URL API_KEY\n# Or use the long-form option:\nnpx typesafeenv validate --vars DB_URL API_KEY\n\n```\n\n```typescript\n# Expected Output:\nValidating environment variables: [ 'DB_URL', 'API_KEY' ]\n✔️ DB_URL is valid: http://example.com (type: string)\n✔️ API_KEY is valid: your-api-key (type: string)\n```\n\n## 🔧 Advanced Configuration\n\nYou can customize **TypeSafeEnv** to suit the needs of your application. For example:\n\n### 🌍 Dynamic Environment Handling\n\nInstead of hardcoding the environment (e.g., production or development), you can dynamically get the current environment using `process.env.NODE_ENV`.\n\n### 🌟 Example:\n\n#\n\n```typescript\nconst currentEnv = process.env.NODE_ENV || \"production\";\nconst configValue = TypeSafeEnv.getEnvSpecificConfig(\"API_KEY\", currentEnv);\n```\n\n## 🚀 Load Environment Variables from External Files\n\n### What this method does:\n\n*Allows you to load `.env` files from different folders by providing their file paths.\n*Stores the variables into an object for easy access.\n*Enables you to retrieve and use environment variables directly in your code.\n*Simplifies the process of managing environment variables in less than a minute.\n\n### 🌟 Example: Using ES6\n\n```typescript\nimport { loadEnvironmentVariables } from \"ts-typesafe-env\";\n```\n\n🔧 Define the Current Directory\nUse the following to determine the directory and filename:\n\n```typescript\nconst __filename = fileUrlToPath(import.meta.url);\n\nconst __dirname = path.dirname(__filename);\n```\n\n📁 Specify the Path to Your `.env` File\nYou can load a `.env` file from any folder with the file path:\n\n```typescript\nconst envfilepath = path.resolve(__dirname, \"./config/.env\");\n\n// Load the environment variables\nconst newENV = loadEnvironmentVariables(envfilepath);\nconsole.log(newENV); // Outputs the parsed environment variables\n```\n\n🛠️ Apply Logic and Use Environment Variables\nAccess the loaded variables in your project like this:\n\n```typescript\ntry {\n  const newENV = loadEnvironmentVariables(envfilepath);\n  console.log(newENV);// Logs the entire `.env` object\n\n  const apiKey = TypeSafeEnv.getString(\"NEW_DB\");\n  console.log(apiKey);/ Outputs the value of NEW_DB\n\n  const max_size = TypeSafeEnv.getNumber(\"MAX_SIZE\");\n  console.log(max_size); // Outputs the value of MAX_SIZE\n  // Example: Get a boolean value\n  const db_sessions = TypeSafeEnv.getBoolean(\"DB_SESSION_NEW\");\n  console.log(db_sessions);// Outputs the value of DB_SESSION_NEW\n} catch (e) {\n  console.error(e);// Logs any errors\n}\n```\n\n### 🌟 Example: Using CommonJS\n\n```typescript\n// Import necessary modules\nconst { loadEnvironmentVariables } = require(\"ts-typesafe-env\");\nconst path = require(\"path\");\n```\n\n📁 Specify the Path to Your `.env` File\nYou can load a `.env` file from any folder with the file path:\n\n```typescript\nconst envfilepath = path.resolve(__dirname, \"./config/.env\");\n\n// Load the environment variables\nconst newENV = loadEnvironmentVariables(envfilepath);\nconsole.log(newENV); // Outputs the parsed environment variables\n```\n\n🛠️ Apply Logic and Use Environment Variables\nAccess the loaded variables in your project like this:\n\n```typescript\ntry {\n  const newENV = loadEnvironmentVariables(envfilepath);\n  console.log(newENV); // Logs the entire `.env` object\n\n  // Example: Access a string value\n  const apiKey = TypeSafeEnv.getString(\"NEW_DB\");\n  console.log(apiKey); // Outputs the value of NEW_DB\n\n  // Example: Access a number value\n  const max_size = TypeSafeEnv.getNumber(\"MAX_SIZE\");\n  console.log(max_size); // Outputs the value of MAX_SIZE\n\n  // Example: Access a boolean value\n  const db_sessions = TypeSafeEnv.getBoolean(\"DB_SESSION_NEW\");\n  console.log(db_sessions); // Outputs the value of DB_SESSION_NEW\n} catch (e) {\n  console.error(e); // Logs any errors\n}\n```\n\n### ✨ Highlights of This Method\n\n- 🛡️ Flexible: Load .env files from any location.\n- 🔒 Type-Safe: Use getString, getNumber, or getBoolean, Etc.. for reliable access.\n- ⚡ Convenient: Quickly integrate and manage environment variables in your project.\n\n## ✔️Handling File Paths in JavaScript/TypeScript (Windows)\n\nWhen working with file paths in JavaScript or TypeScript, especially when dealing with `path.resolve`, it’s essential to handle Windows-style paths carefully. Here's how you can correctly handle the file path:\n\n### Problem\n\n⚠️ If youprovide a Windows path directly like this:\n\n```typescript\nconst envFilePath = path.resolve(\n  __dirname,\n  \"D:Program Files (x86)New folder.env\"\n);\n//You might encounter issues because backslashes (\\) are escape characters in strings.\n```\n\n💡Solution: Use Forward Slashes\nUse forward slashes (/) instead of backslashes. Node.js automatically handles them correctly across platforms:\n\n```typescript\nconst envFilePath = path.resolve(\n  __dirname,\n  \"D:/Program Files (x86)/New folder/.env\"\n);\n\nOR;\nconst folderPath = \"D:/Program Files (x86)/New folder\";\nconst envFilePath = path.resolve(__dirname, `${folderPath}/.env`);\n```\n\n### ⚙️ Custom Validation (For Contributors)\n\nIf the built-in validation methods don't meet your needs, **you can extend the package** by creating **custom validators** for more complex logic. This customization is intended for contributors who want to enhance the functionality of **Ts-Typesafeenv**.\n\n#### Example of Adding a Custom Validator:\n\nTo add custom validation logic, you can extend the `TypeSafeEnv` class in your local development environment:\n\n```js\n// Custom Validator Example in the package code\nclass CustomValidator {\n  static validateApiKey(apiKey) {\n    if (!apiKey || apiKey.length !== 32) {\n      throw new Error(\"Invalid API Key. It must be 32 characters long.\");\n    }\n    return apiKey;\n  }\n}\n\n// Usage within the package code\nconst apiKey = TypeSafeEnv.getString(\"API_KEY\");\nCustomValidator.validateApiKey(apiKey);\n```\n\n📜 License\n\nThis project is licensed under the MIT License - see the LICENSE file for details\n🌐 [For More Information](https://github.com/Innocent6303/typesafe-env/blob/main/LICENSE)\n\nVisit the [GitHub repository](https://github.com/Innocent6303/typesafe-env). for detailed documentation and contribution guidelines.\n\n### **💬 Summary**\n\n**Ts-Typesafeenvv** simplifies the process of validating environment variables, making it ideal for large-scale projects. By leveraging the built-in functions and CLI, developers can easily ensure their environment configuration is correct, minimizing the risk of runtime errors caused by missing or invalid variables.\n\nWith **Ts-Typesafeenv**, you no longer need to manually access `process.env` for every variable, which makes your code cleaner, more maintainable, and reliable.\n\n\u003e Say goodbye to the hassle of managing environment variables manually—**Ts-Typesafeenvv** does it all for you!\n\n---\n\n#\n\n- **Easy to use**\n- **Built-in validation functions**\n- **CLI support for quick validation**\n- **No more manual access to `process.env`**\n\n#\n\n---\n\n#\n\n### Made with ❤️ by **Abdul Mujeeb**\n\nA passion project crafted with care to help developers manage environment variables with ease. Thank you for using **Ts-Typesafeenv**!\n\n\u003e \"Code is like humor. When you have to explain it, it’s bad. \" – **_A M_**\n\n---\n\n#\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmujeebdev3%2Ftypesafe-env","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmujeebdev3%2Ftypesafe-env","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmujeebdev3%2Ftypesafe-env/lists"}