Utilizing various settings using `.env` files in NodeJs

As I work on building a backend in nodejs, one of the key considerations is how to incorporate an environment configuration into the project. I am envisioning a structure where there is a /config folder housing my envparser.ts (still brainstorming a catchier name for this ^^) which would interpret my .env files and convert them into regular javascript constants. Using scripts within my package.json, my goal is to be able to seamlessly switch between different environments. However, I'm currently stuck on the question of how to effectively alternate between multiple .env files using dotenv.

File Structure:

config/
   .env.development
   .env.production
   envparser.ts

Scripts:

yarn start
yarn start -p/-production //Alternatively, explore a different syntax for changing environments

Answer №1

To access your environment variables stored in different .env.* files, you can make use of the dotenv package.


If you need to switch between various environments, you can do so by changing the value of the NODE_ENV variable when running different commands specified in your package.json.

For example:

"scripts": {
    "start": "NODE_ENV=development nodemon index.js",
    "deploy": "NODE_ENV=production node index.js"
}

Afterwards, you can access these configurations in your index.js file like this:

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

Answer №2

You can implement something similar to this in the scripts section of your package.json file

"start:dev": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.development", 
"start:prod": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.production"

To start the server in development mode, run npm run start:dev

To start the server in production mode, run npm run start:prod

Answer №3

To include the following snippet in your scripts section of package.json:

"dev": "nodemon -r dotenv/config index.js"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while attempting to launch a Docker node container on Windows 10 system

As a beginner in the world of Docker, I decided to experiment with running simple examples on both my Windows 10 PC and Mac simultaneously. Interestingly, the example runs smoothly on my Mac but encounters an issue on the Windows machine. After setting up ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

Removing spaces within brackets on dynamic properties for objects can be achieved by utilizing various methods such as

I've encountered an issue with my code that involves getting spaces within square brackets for the dynamic properties of an object. Even after searching through Code Style/Typescript/Spaces, I couldn't find any settings to adjust this. Could thes ...

Is there a way to remove the contents of a list along with the list itself? When removing a certain element x from list y, can we also delete y altogether if

I am managing two different collections, Classrooms Students Here is the schema for each: **CLASSROOM SCHEMA** const mongoose = require('mongoose'); const classroomSchema = new mongoose.Schema({ classroomname: { type: String }, cr ...

Webpack returns an undefined error when attempting to add a JavaScript library

I am a newcomer to webpack and I am attempting to incorporate skrollr.js into my webpack setup so that I can use it as needed. However, I am unsure of the correct approach for this. After some research, I have found that I can either use an alias or export ...

The repairDatabase function cannot be found in the Collection.rawDatabase() method

Seeking guidance on repairing a database within Meteor. Currently executing the following code: Meteor.methods({ 'repairDB'(){ Users.rawDatabase().repairDatabase(); return true; } }); Encountering the following error: I20170630-18: ...

Embrace the power of Angular2: Storing table information into

Custom table design Implement a TypeScript function to extract data from an array and populate it into a stylish table. ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Leveraging npm packages in Meteor's Angular 1.3 framework

Although it may sound like a silly question, I am still confused. It has been said that Meteor has native support for npm modules in version 1.3. I am currently using Meteor with Angular integration. From the tutorial, it appears that using npm modules sh ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

Ways to execute JavaScript once the connection has been established?

Being new to Node.js, I am attempting to modify the example of the Smartphone Remote Control with Node.js and Socket.io by Nick Anastasov to eliminate the need for a password. In the original code, the app.js file sends { access : 'granted' } af ...

What is the most efficient method for inserting values into the results of a query using Mongoose?

My express api includes an endpoint that executes a findById query on the model Community. I then need to inject a key value pair into the result based on a query made to another model. However, my initial approach did not produce the desired outcome. The ...

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

The Conundrum of Angular 5 Circular Dependencies

I've been working on a project that involves circular dependencies between its models. After reading through this StackOverflow post and its suggested solutions, I realized that my scenario might not fit into the category of mixed concerns often assoc ...

Ways to determine the number of duplicate items in an Array

I have an array of objects that contain part numbers, brand names, and supplier names. I need to find a concise and efficient way to determine the count of duplicate objects in the array. [ { partNum: 'ACDC1007', brandName: 'Electric&apo ...

"Errors are encountered when attempting to launch a server as a Linux service while using the

I have been working on creating a simple API for myself using a Node.js/Express server hosted on Digital Ocean. In my server file, I am using the following code snippet: var data = fs.readFileSync('path/to/data.json','utf8'); This wor ...

Exploring the concept of an asynchronous error in Mocha testing

Dealing with a block of code that attempts to reconnect to Redis in case the connection is lost and throws an error if it fails to re-establish. However, I am struggling to successfully test this error throwing block using mocha and chai. The test scenari ...

I encountered an issue when trying to establish a connection between the environment and mongoose

This code is found in my .env file: DB_URL=mongodb://localhost:27017/ecomm The connection.js file contains the following code: const mongoose=require('mongoose') const {DB_URL}=process.env console.log(process.env) async function createConnectio ...

Utilizing Node and Socket.io to transmit data periodically via websockets from a CSV file

I am relatively new to working with Node.js and Express.js. My goal is to set up a websocket server that can send CSV data at irregular intervals stored within the file itself, line by line. The structure of the CSV looks something like this: [timeout [ms] ...

The API endpoint code functions perfectly in Express, but encounters an error when integrated into Next.js

Express Code: app.get('/', async (req, res) => { const devices = await gsmarena.catalog.getBrand("apple-phones-48"); const name = devices.map((device) => device.name); res.json(name); }) Nextjs Code: import {gsmarena} ...