<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jaimin Prajapati</title>
    <description>The latest articles on DEV Community by Jaimin Prajapati (@jaiprajapati3).</description>
    <link>https://dev.to/jaiprajapati3</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1654704%2F1f58bf57-938f-40ee-8f5a-fbb7ad28b3e4.jpg</url>
      <title>DEV Community: Jaimin Prajapati</title>
      <link>https://dev.to/jaiprajapati3</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jaiprajapati3"/>
    <language>en</language>
    <item>
      <title>Validating Environment Variables with Joi in NodeJS</title>
      <dc:creator>Jaimin Prajapati</dc:creator>
      <pubDate>Thu, 25 Jul 2024 11:32:46 +0000</pubDate>
      <link>https://dev.to/jaiprajapati3/validating-environment-variables-with-joi-in-nodejs-13mo</link>
      <guid>https://dev.to/jaiprajapati3/validating-environment-variables-with-joi-in-nodejs-13mo</guid>
      <description>&lt;p&gt;Imagine you’re on the final leg of a project, everything is set to go live, and boom! The app crashes because an environment variable is missing or misconfigured. Sound familiar? If you’ve been there, you know the frustration. But fear not, because Joi is here to save the day!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzrsse8cbsja8ydjujznt.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzrsse8cbsja8ydjujznt.jpg" alt="Image description" width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog post, we’ll explore how we can use Joi to validate environment variables and set default values, ensuring your application runs smoothly across all environments.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Problem&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Environment variables are like the unsung heroes of our applications. They hold the keys to sensitive information, database connections, and various configuration settings. But with great power comes great responsibility:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Missing Variables:&lt;/strong&gt; “Why isn’t my app connecting to the database?” Oops, forgot to set DATABASE_URL.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Incorrect Data Types:&lt;/strong&gt; “Why is my server listening on port ‘three thousand’?” Typo in the PORT variable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Inconsistent Configuration:&lt;/strong&gt; Development works fine, but production is a nightmare.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lack of Defaults:&lt;/strong&gt; The app fails if certain variables aren’t set.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These issues can lead to sleepless nights and frantic debugging sessions. But what if you could avoid them altogether?&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Enter Joi&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Joi is a powerful schema description and data validation library for JavaScript. With Joi, you can define a schema for your environment variables, ensuring they meet specific criteria and setting default values where necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Steps to Validate and Set Defaults with Joi
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Install Joi &amp;amp; dotenv&lt;/strong&gt;&lt;br&gt;
First, you need to install Joi. Open your terminal and run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install joi dotenv
# dotenv if you are reading env variables from .env file
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create a Configuration File&lt;/strong&gt;&lt;br&gt;
Create a file called config.js. This is where we'll define our schema and validate the environment variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Joi = require('joi');
const dotenv = require('dotenv');

// Load environment variables from .env file
dotenv.config();

// Define the schema
const envSchema = Joi.object({
  NODE_ENV: Joi.string().valid('development', 'production', 'test')
    .default('development'),
  PORT: Joi.number().default(3000),
  DATABASE_URL: Joi.string().uri().required(),
  API_KEY: Joi.string().required(),
  // Add more variables as needed
}).unknown(); // Allow unknown keys

// Validate the environment variables
const { error, value: envVars } = envSchema.validate(process.env, 
  { abortEarly: false }
);

if (error) {
  console.error('Config validation error(s):');
  error.details.forEach(detail =&amp;gt; {
    console.error(`- ${detail.message}`);
  });
  throw new Error('Environment variables validation failed.');
}

// Export the validated and normalized environment variables
module.exports = {
  nodeEnv: envVars.NODE_ENV,
  port: envVars.PORT,
  databaseUrl: envVars.DATABASE_URL,
  apiKey: envVars.API_KEY,
  // Add more variables as needed
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Use the Configuration in Your Application&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const config = require('./config');

console.log(`Server is running on port ${config.port}`);
// Use config.databaseUrl, config.apiKey, etc.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example with Errors&lt;/strong&gt;&lt;br&gt;
Let’s say we have the following .env file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;NODE_ENV=development
PORT=not_a_number
DATABASE_URL=
API_KEY=my_api_key
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we run our application, Joi will validate these variables. Here’s what happens:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;PORT&lt;/strong&gt; is set to not_a_number, which is not a valid number.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DATABASE_URL&lt;/strong&gt; is empty, which is invalid since it’s a required field.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When Joi validates these variables, it will throw errors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jaimin:~/joi-validate-env$ node index.js
Config validation error(s):
- "PORT" must be a number
- "DATABASE_URL" is not allowed to be empty
/home/jaimin/joi-validate-env/config.js:27
  throw new Error('Environment variables validation failed.');
  ^

Error: Environment variables validation failed.
    at Object.&amp;lt;anonymous&amp;gt; (/home/jaimin/joi-validate-env/config.js:27:9)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.&amp;lt;anonymous&amp;gt; (/home/jaimin/joi-validate-env/index.js:1:16)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This detailed error report helps quickly identify and fix issues in the environment configuration.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why Use Joi?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Consistency&lt;/strong&gt;&lt;br&gt;
No more “works on my machine” moments. Joi ensures all necessary environment variables are set and have correct types across different environments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Default Values&lt;/strong&gt;&lt;br&gt;
Set default values for variables, reducing the risk of runtime errors due to missing settings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Early Error Detection&lt;/strong&gt;&lt;br&gt;
Catch configuration errors early in the startup phase, preventing the application from running with invalid settings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Schema Documentation&lt;/strong&gt;&lt;br&gt;
Acts as a self-documenting schema for environment variables, making it easier for new developers to understand the required configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Flexibility&lt;/strong&gt;&lt;br&gt;
Allows for complex validation logic, such as value ranges, specific formats, and custom validation functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using Joi to validate environment variables and set default values is like having a safety net for your application. It ensures your app runs smoothly across all environments, sparing you from unexpected crashes and hours of debugging.&lt;/p&gt;

&lt;p&gt;By adopting this approach, you can avoid common pitfalls related to environment variables and focus on building features that add value to your users. So go ahead, integrate Joi into your project, and sleep soundly knowing your environment variables are in good hands.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
