<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jayant Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Jayant Choudhary on Medium]]></description>
        <link>https://medium.com/@jayantchoudhary271?source=rss-4cf0f582cec5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*myqkMvQWf1CggGbd</url>
            <title>Stories by Jayant Choudhary on Medium</title>
            <link>https://medium.com/@jayantchoudhary271?source=rss-4cf0f582cec5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:31:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayantchoudhary271/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streamline Your Processes with Node.js Cron Jobs]]></title>
            <link>https://medium.com/@jayantchoudhary271/streamline-your-processes-with-node-js-cron-jobs-2a77e341796d?source=rss-4cf0f582cec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a77e341796d</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[node-cron]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jayant Choudhary]]></dc:creator>
            <pubDate>Sat, 06 Apr 2024 11:24:34 GMT</pubDate>
            <atom:updated>2024-04-06T11:24:34.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*nIGezbRjgu6HXjq-GPuNEA.png" /><figcaption>Cron Job</figcaption></figure><p><strong>Demystifying Node-cron: <br></strong>A Versatile Scheduling Solution for Node.js. Simplify task automation with its intuitive interface inspired by Unix cron syntax. Node-cron empowers you to automate various tasks effortlessly, from mundane daily email dispatches to intricate database upkeep operations.</p><p><strong>Harnessing the Benefits of Node-cron</strong></p><p><strong>1. Streamlined Cron Syntax</strong><br>Node-cron simplifies task scheduling with its intuitive cron syntax. Say goodbye to convoluted cron expressions and embrace a straightforward format that resembles everyday language. Schedule tasks effortlessly, whether it’s “every minute” or “Monday at 10:00 PM.”</p><p><strong>2. Flexible Scheduling Options</strong><br>Node-cron offers unparalleled flexibility in scheduling. Whether you require one-time executions, recurring tasks, or custom intervals, Node-cron adapts seamlessly to your needs. Its versatility caters to a wide array of automation requirements.</p><p><strong>3. User-Friendly and Lightweight</strong><br>Developers appreciate Node-cron for its ease of use and lightweight nature. It seamlessly integrates into Node.js projects, catering to users of all expertise levels. Moreover, Node-cron maintains project efficiency by keeping dependencies minimal, ensuring optimal performance.</p><p><strong>4. Effortless Integration</strong><br>Node-cron effortlessly integrates with other Node.js packages and libraries. This seamless compatibility enables you to leverage its capabilities alongside a diverse range of functionalities from the Node.js ecosystem.</p><h3>Getting Started with Node-cron</h3><p>Let’s embark on your journey with node-cron:</p><h3>1. Initialize a Node.js Project</h3><p>If you haven’t already, start a Node.js project using npm init or yarn init.</p><h3>2. Install Node-cron</h3><p>Use npm or yarn to install the node-cron package:</p><pre>npm install node-cron<br>#or<br>yarn add node-cron</pre><h3>3. Import Node-cron</h3><p>Incorporate node-cron into your Node.js application:</p><pre>const cron = require(&#39;node-cron&#39;);</pre><h3>4. Define and Schedule a Cron Job</h3><p>Let’s dive into a more complex example. Suppose you need to process and upload data to a remote server every Monday at 10:00 PM:</p><pre>const cron = require(&#39;node-cron&#39;);<br><br>function weeklyTask() {<br>  console.log(&#39;Running weekly task...&#39;);<br>}<br><br>// Schedule the cron job (runs every Monday at 10:00 PM)<br>cron.schedule(&#39;0 22 * * 1&#39;, weeklyTask);</pre><p>In this example, the processDataAndUpload function will execute daily at precisely 10:00 PM</p><h3>5. Start and Stop the Cron Job</h3><p>To activate the cron job, simply call the start method:</p><pre>cron.start();</pre><p>Should you need to gracefully halt the cron job, utilize the stop method:</p><pre>cron.stop();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a77e341796d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an AWS S3 Bucket Using Terraform]]></title>
            <link>https://medium.com/@jayantchoudhary271/creating-an-aws-s3-bucket-using-terraform-2640c74aabd9?source=rss-4cf0f582cec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2640c74aabd9</guid>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Jayant Choudhary]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 17:24:57 GMT</pubDate>
            <atom:updated>2024-02-18T17:24:57.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you looking to streamline your infrastructure deployment process on Amazon Web Services (AWS)? Look no further than Terraform, a powerful Infrastructure as Code (IaC) tool that allows you to define and provision your cloud infrastructure in a declarative manner. In this guide, we’ll walk you through the steps to deploy an AWS S3 bucket using Terraform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rk0al-gEjzYa5r3KGf4g2w.jpeg" /></figure><h4>Prerequisites</h4><p>Before getting started, ensure you have the following:</p><ul><li>AWS account with appropriate permissions</li><li>Terraform installed on your local machine</li><li>Access key and secret key generated from your AWS account</li></ul><h3>Step 1: Configure AWS Credentials</h3><p>Firstly, set up your AWS credentials by running the command aws configure in your terminal. Enter your AWS Access Key ID and AWS Secret Access Key when prompted.</p><h3>Step 2: Navigate to Your Terraform Configuration Directory</h3><p>Next, navigate to the directory where your Terraform configuration files are located. This is where you’ll define your AWS resources.</p><h3>Step 3: Initialize Terraform</h3><p>Run terraform init to initialise Terraform in your project directory. This command will download the necessary providers and initialise your Terraform environment.</p><h3>Step 4: Define Your Terraform Configuration</h3><p>Now, let’s define the Terraform configuration for deploying an S3 bucket. Open your preferred text editor and create a file named main.tf with the following content:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;ap-south-1&quot; // Specify the AWS region where resources will be created<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;bucket&quot; {<br>  bucket = &quot;your-bucket-name&quot; // Enter Bucket Name<br><br>  tags = {<br>    Name        = &quot;My bucket&quot;<br>  }<br>}</pre><p>Make sure to replace &quot;your-bucket-name&quot; with your desired bucket name.</p><h3>Step 5: Plan and Apply Your Terraform Configuration</h3><p>Run terraform plan to preview the changes Terraform will make to your infrastructure. This step ensures you understand the actions Terraform will take.</p><p>Once you’re satisfied with the plan, execute terraform apply and type yes when prompted to apply the changes. Terraform will create the S3 bucket in your specified AWS region.</p><h3>Optional Step: Destroy Resources</h3><p>If you need to clean up your resources, you can run terraform destroy to remove the S3 bucket and associated resources. This step is optional but useful for managing costs and cleaning up unused resources.</p><h3>Conclusion</h3><p>Congratulations! You’ve successfully deployed an AWS S3 bucket using Terraform. With Terraform’s declarative syntax and AWS provider, you can easily manage and scale your infrastructure as code, making deployment and management a breeze. Explore further and integrate more AWS services into your Terraform configuration to build robust and scalable cloud environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2640c74aabd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Role-Based Access Control (RBAC) in Node.Js and Express.Js]]></title>
            <link>https://medium.com/@jayantchoudhary271/building-role-based-access-control-rbac-in-node-js-and-express-js-bc870ec32bdb?source=rss-4cf0f582cec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc870ec32bdb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[role-based-access-control]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jayant Choudhary]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 08:27:38 GMT</pubDate>
            <atom:updated>2023-12-21T08:27:38.350Z</atom:updated>
            <content:encoded><![CDATA[<p>Role-Based Access Control (RBAC) stands as a pivotal pillar in ensuring robust application security. Offering a systematic framework, RBAC empowers organisations and applications to meticulously govern and limit resource access in accordance with users’ designated roles.</p><p>This in-depth guide delves into the core principles of RBAC, elucidates its advantages, and provides a step-by-step walkthrough for integrating RBAC seamlessly into a Node.js application.</p><figure><img alt="RBAC" src="https://cdn-images-1.medium.com/max/1024/1*yXEPJz-DNzXHsV-4IVFUgQ.jpeg" /></figure><h3>Project Structure</h3><p>Below is the fundamental project structure that will serve as the foundation for this tutorial:</p><pre>rbac-project/<br>│<br>├── package.json<br>├── package-lock.json<br>├── server.js<br>|<br>├── models/<br>│   └── user.js<br>|<br>├── routes/<br>│   └── auth.js<br>│   └── records.js<br>|<br>├── controllers/<br>│   └── authController.js<br>│   └── recordsController.js<br>|<br>├── middleware/<br>│   └── rbacMiddleware.js<br>│<br>└── config/<br>    └── roles.json</pre><h3>Defining Roles and Permissions</h3><p>Let’s start by defining some roles and permissions for our rbac project.</p><p>Create a roles.json file in the config/ directory:</p><pre>{<br>  &quot;roles&quot;: [<br>    {<br>      &quot;name&quot;: &quot;admin&quot;,<br>      &quot;permissions&quot;: [<br>        &quot;create_record&quot;,<br>        &quot;read_record&quot;,<br>        &quot;update_record&quot;,<br>        &quot;delete_record&quot;<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;manager&quot;,<br>      &quot;permissions&quot;: [<br>        &quot;create_record&quot;,<br>        &quot;read_record&quot;,<br>        &quot;update_record&quot;<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;employee&quot;,<br>      &quot;permissions&quot;: [<br>        &quot;create_record&quot;,<br>        &quot;read_record&quot;<br>      ]<br>    }<br>  ]<br>}</pre><p>Here, we’ve defined three roles: “admin,” “manager,” and “employee,” each with different sets of permissions related to task management.</p><h3>Storing Role and Permission Data</h3><p>Now, let’s create models to represent roles and permissions. In the models/ directory, create a file named role.js:</p><pre>// models/role.js<br><br>const roles = require(&#39;../config/roles.json&#39;);<br><br>class Role {<br>  constructor() {<br>    this.roles = roles.roles;<br>  }<br><br>  getRoleByName(name) {<br>    return this.roles.find((role) =&gt; role.name === name);<br>  }<br><br>  getRoles() {<br>    return this.roles;<br>  }<br>}<br><br>module.exports = Role;</pre><p>We’ve created a Role class that reads the roles and permissions from the roles.json file. We also provide methods to retrieve roles by name or get a list of all roles.</p><p>Next, create a permissions.js file in the same models/ directory:</p><pre>// models/permissions.js<br><br>class Permissions {<br>  constructor() {<br>    this.permissions = [];<br>  }<br><br>getPermissionsByRoleName(roleName) {<br>    const role = roles.roles.find((r) =&gt; r.name === roleName);<br>    return role ? role.permissions : [];<br>  }<br>}<br>module.exports = Permissions;</pre><p>The Permissions class allows us to fetch permissions based on a role&#39;s name.</p><p>We&#39;ll use these models when assigning roles to users and checking permissions in the RBAC middleware.</p><h3>Implementing User Authentication</h3><p>User authentication is a fundamental part of RBAC. We’ll use a popular Node.js library called “Passport” to handle authentication. Here’s how you can set up Passport for your Node.js application:</p><p>First, install the required dependencies:</p><pre>npm install mongoose passport passport-local passport-local-mongoose express-session</pre><p>Now, create a user model using Mongoose and Passport in the models/user.js file:</p><pre>// models/user.js<br><br>const mongoose = require(&#39;mongoose&#39;);<br>const passportLocalMongoose = require(&#39;passport-local-mongoose&#39;);<br><br>const userSchema = new mongoose.Schema({<br>  username: String,<br>  password: String,<br>  role: String,<br>});<br><br>userSchema.plugin(passportLocalMongoose);<br><br>const User = mongoose.model(&#39;User&#39;, userSchema);<br><br>module.exports = User;</pre><p>Utilised passport-local-mongoose for user authentication.</p><h3>Role Assignment</h3><p>Now, when a user registers or is created, we need to assign a role to them. In the controllers/authController.js file, add the following code:</p><pre>// controllers/authController.js<br><br>const User = require(&#39;../models/user&#39;);<br>const Role = require(&#39;../models/role&#39;);<br><br>// Register a new user with a role<br>exports.registerUser = (req, res) =&gt; {<br>  const { username, password, role } = req.body;<br>  const user = new User({ username, role });<br><br>  User.register(user, password, (err) =&gt; {<br>    if (err) {<br>      console.log(err);<br>      return res.status(500).json({ error: err.message });<br>    }<br>    res.json({ message: &#39;User registered successfully&#39; });<br>  });<br>};</pre><p>In the above code, we create a new user and specify their role during registration.</p><h3>Creating RBAC Middleware</h3><p>Middleware in Node.js is essential for handling tasks such as route protection and user authorization. We’ll create RBAC middleware to check if a user has the necessary permissions to access a specific route.</p><p>In the middleware/rbacMiddleware.js file, add the following code:</p><pre>// middleware/rbacMiddleware.js<br><br>const Role = require(&#39;../models/role&#39;);<br>const Permissions = require(&#39;../models/permissions&#39;);<br><br>// Check if the user has the required permission for a route<br>exports.checkPermission = (permission) =&gt; {<br>  return (req, res, next) =&gt; {<br>    const userRole = req.user ? req.user.role : &#39;anonymous&#39;;<br>    const userPermissions = new Permissions().getPermissionsByRoleName(userRole);<br><br>    if (userPermissions.includes(permission)) {<br>      return next();<br>    } else {<br>      return res.status(403).json({ error: &#39;Access denied&#39; });<br>    }<br>  };<br>};</pre><p>In this middleware, we extract the user’s role from their session and check if the role has the required permission to access a route. If the user has the necessary permission, they are allowed to proceed; otherwise, a “403 Forbidden” response is sent.</p><h3>Protecting Routes</h3><p>To protect specific routes using the RBAC middleware, import the middleware function and apply it to the desired routes in your route handlers.</p><p>Here’s an example of how to protect a route using the checkPermission middleware:</p><pre>// routes/records.js<br><br>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const rbacMiddleware = require(&#39;../middleware/rbacMiddleware&#39;);<br><br>// Import your controller<br>const recordsController = require(&#39;../controllers/recordsController&#39;);<br><br>// Protect the route with RBAC middleware<br>router.get(&#39;/records&#39;, rbacMiddleware.checkPermission(&#39;read_record&#39;), recordsController.getAllRecords);<br><br>module.exports = router;</pre><p>Now, the /tasks route is protected, and only users with the &quot;read_task&quot; permission will be able to access it.</p><h3>Building a Simple Records Management System</h3><p>Let’s start by defining the basic routes for our Record Management System. Create a new file named records.js in the routes/ directory:</p><pre>// routes/records.js<br><br>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const rbacMiddleware = require(&#39;../middleware/rbacMiddleware&#39;);<br><br>// Import your controller<br>const recordsController = require(&#39;../controllers/recordsController&#39;);<br><br>// Protect the routes with RBAC middleware<br>router.get(&#39;/records&#39;, rbacMiddleware.checkPermission(&#39;read_record&#39;), recordsController.getAllRecord);<br>router.post(&#39;/records&#39;, rbacMiddleware.checkPermission(&#39;create_record&#39;), recordsController.createRecord);<br>router.put(&#39;/records/:id&#39;, rbacMiddleware.checkPermission(&#39;update_record&#39;), recordsController.updateRecord);<br>router.delete(&#39;/records/:id&#39;, rbacMiddleware.checkPermission(&#39;delete_record&#39;), recordsController.deleteRecord);<br><br>module.exports = router;</pre><p>In this code, we have defined routes for listing, creating, updating, and deleting records. Each route is protected by the RBAC middleware, which checks the user’s permissions before allowing access.</p><h3>Defining Roles and Permissions</h3><p>Before we can assign roles to users, let’s define the roles and permissions for our application. In the config/roles.json file, specify the roles and their associated permissions:</p><pre>{<br>  &quot;roles&quot;: [<br>    {<br>      &quot;name&quot;: &quot;admin&quot;,<br>      &quot;permissions&quot;: [&quot;create_record&quot;, &quot;read_record&quot;, &quot;update_record&quot;, &quot;delete_record&quot;]<br>    },<br>    {<br>      &quot;name&quot;: &quot;manager&quot;,<br>      &quot;permissions&quot;: [&quot;create_record&quot;, &quot;read_record&quot;, &quot;update_record&quot;]<br>    },<br>    {<br>      &quot;name&quot;: &quot;employee&quot;,<br>      &quot;permissions&quot;: [&quot;create_record&quot;, &quot;read_record&quot;]<br>    }<br>  ]<br>}</pre><p>We’ve defined three roles: “admin,” “manager,” and “employee,” each with different levels of access.</p><h3>Implementing Authentication and Authorization</h3><p>In the controllers/authController.js file, implement user registration and login functionalities:</p><pre>// controllers/authController.js<br><br>const User = require(&#39;../models/user&#39;);<br>const Role = require(&#39;../models/role&#39;);<br><br>// Register a new user with a role<br>exports.registerUser = (req, res) =&gt; {<br>  const { username, password, role } = req.body;<br>  const user = new User({ username, role });<br><br>  User.register(user, password, (err) =&gt; {<br>    if (err) {<br>      console.error(err);<br>      return res.status(500).json({ error: err.message });<br>    }<br>    res.json({ message: &#39;User registered successfully&#39; });<br>  });<br>};<br><br>// Login a user and create a session<br>exports.loginUser = (req, res) =&gt; {<br><br>  const { username, password } = req.body;<br><br>  User.authenticate(username, password, (err, user) =&gt; {<br>    if (err || !user) {<br>      return res.status(401).json({ error: &#39;Invalid credentials&#39; });<br>    }<br><br>    // Create a new session and store user id<br>    req.session.userId = user._id; <br><br>    res.json({ message: &#39;Login successful&#39; });<br><br>  });<br><br>};</pre><p>Here is the index.js file</p><pre>// Import required modules and files<br>const express = require(&#39;express&#39;);<br>const app = express();<br>const bodyParser = require(&#39;body-parser&#39;);<br>const authRoutes = require(&#39;./routes/auth&#39;);<br>const recordsRoutes = require(&#39;./routes/record&#39;);<br>const authController = require(&#39;./controllers/authController&#39;);<br>const recordsController = require(&#39;./controllers/recordsController&#39;);<br>const rbacMiddleware = require(&#39;./middleware/rbacMiddleware&#39;);<br><br>// Configure middleware<br>app.use(bodyParser.json());<br><br>// Define routes<br>app.use(&#39;/auth&#39;, authRoutes);<br>app.use(&#39;/records&#39;, rbacMiddleware.checkRole(&#39;user&#39;), recordsRoutes);<br><br>// Start the server<br>const PORT = process.env.PORT || 4000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><p>This index.js file sets up an Express.js server, imports the necessary modules, and configures the required middleware.</p><p>It also defines routes for authentication and tasks, utilizing the rbacMiddleware to check the user&#39;s role before allowing access to the records routes.</p><p>By implementing RBAC, you can significantly enhance the security of your Node.js applications, control user access effectively, and reduce the risk of security breaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc870ec32bdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.Js: Upgrade your .env file using this powerful tool efficiently at scale.]]></title>
            <link>https://medium.com/@jayantchoudhary271/node-js-upgrade-your-env-file-using-this-powerful-tool-efficiently-at-scale-1899c5a90f3a?source=rss-4cf0f582cec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1899c5a90f3a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jayant Choudhary]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 09:03:17 GMT</pubDate>
            <atom:updated>2023-09-08T09:03:17.451Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Node.Js: Upgrade your .env file using this powerful tool efficiently at scale.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*U_VFaIJVZG-SzJ8iP5OSng.png" /></figure><p>When it comes to developing applications, securely managing sensitive information such as API keys, database credentials, and configuration settings is of paramount importance. Effectively handling these environment variables throughout the development lifecycle presents a ubiquitous challenge. It’s evident that relying solely on .env files has become insufficient for several compelling reasons.</p><p>In this article, I explore the best practices for efficiently managing environment variables at scale within your Node application using <br><a href="https://infisical.com/">Infisical</a></p><h3>What is Infisical?</h3><p><a href="https://infisical.com/">Infisical</a> is an open-source secret management platform that offers end-to-end encryption for securely storing environment variables. It can be self-hosted on your infrastructure, boasts comprehensive documentation, and features an aesthetically pleasing user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CSOHNI1_HpzKqJWnF2Pyg.png" /><figcaption>Infisical</figcaption></figure><p>Its Node SDK enables you to retrieve environment variables dynamically at runtime, whether you are in the midst of local development or running your application in a production environment.</p><h3>Getting started</h3><p>Before you can retrieve environment variables for your Node application, you must first add them to a project in Infisical Cloud or within a self-hosted instance of <a href="https://infisical.com/">Infisical</a>.</p><p>Now, let’s begin the setup process.</p><p>First, install the infisical-node package in your project:</p><pre>$ npm install infisical-node --save</pre><p>Next, import the SDK and create a client instance with your <a href="https://infisical.com/docs/documentation/platform/token">Infisical Token</a>:</p><pre>import InfisicalClient from &quot;infisical-node&quot;;<br><br>const client = new InfisicalClient({<br>  token: &quot;your_infisical_token&quot;<br>});</pre><p>To ensure optimal performance, I highly recommend creating a single instance of the Infisical client and exporting it for universal use throughout your entire application. This approach is beneficial because the Node SDK implements a built-in caching mechanism, which stores and periodically updates secrets, reducing unnecessary calls. This caching feature simplifies the synchronization of environment variables, especially when dealing with scale.</p><p>Furthermore, I suggest storing the Infisical Token in a .env file during local development or as the sole environment variable in your production environment. This practice eliminates the need to hardcode the token directly into your application and allows you to utilize it for retrieving the rest of your environment variables.</p><p>Now, you can utilize the client to fetch secrets for your application on-demand:</p><pre>app.get(&quot;/&quot;, async (req, res) =&gt; {<br>  // Asynchronously fetch the secret named &quot;NAME&quot; from Infisical<br>  const name = await client.getSecret(&quot;NAME&quot;);<br>  <br>  // Send a response containing the retrieved secret value<br>  res.send(`Hello! My name is: ${name.secretValue}`);<br>});</pre><p>That’s it!</p><p>With this setup, your application can now request environment variables from Infisical whenever they are needed. You now have the capability to centrally manage all the environment variables for your Node application, helping you avoid any issues related to missing or improperly configured environment variables.</p><p>For a deeper understanding of how to effectively manage environment variables, I recommend delving into the documentation to explore additional features and best practices.</p><h4><strong>But, you’re still using a .env file…</strong></h4><p>However, there’s a point worth clarifying about the use of a .env file, which may have raised a question for some readers: “If the Infisical Token used to fetch other environment variables is stored in a .env file, doesn’t that defeat the purpose of the tool?”</p><p>The answer is no.</p><p>As previously mentioned, the primary goal of the recommended approach is to maintain synchronization of environment variables across your development team. Often, new environment variables are introduced into a codebase, but updates to .env files are overlooked, leading to potential application crashes. This problem becomes more pronounced as your infrastructure grows, giving rise to what is known as “secret sprawl.” In contrast, Infisical offers a solution that centralizes your environment variables, allowing you to update them in one place and seamlessly deliver them to your entire team and infrastructure, from development to production. This approach differs from the common practice of directly storing numerous environment variables in .env files.</p><h3>Conclusion</h3><p>In conclusion, <a href="https://infisical.com/">Infisical</a> is an excellent platform for simplifying the management of environment variables for both individuals and teams. Being open-source and equipped with a convenient Node SDK, it provides the capability to retrieve environment variables for your Node applications dynamically when needed, enhancing your overall development and deployment workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1899c5a90f3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>