How to access ExpressJS env variables in an API endpoint ? - GeeksforGeeks

04 May, 2021
Using environmental values allows one to configure values in a software/application from outside the software/application itself. This ensures that one doesn’t have to store sensitive data in the code itself. It also helps in reconfiguring the settings in an application without redeploying it.
In this article, we’ll create a RESTful API using Node and Express which will fetch an environment variable from a .env file and return its value as a response.
Prerequisite:
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser.Express.js is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features.
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser.
Express.js is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features.
Follow the below steps to access env variables in an API endpoint:
Step 1: We’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options.
npm init
Step 2: We’ve to install the express and .env packages.
npm install express dotenv --save
Step 3: Create a file index.js, the entry point of this application is going to be the index.js file. All of our business logic will go here. The REST API will contain only a single route which will return the environment variable that we’re going to set.
Javascript
const express = require('express');  // Initialize appconst app = express();  // Assign routeapp.use('/', (req, res, next) => {  res.send('Hello World');});  // Start serverapp.listen(5000, () => {  console.log('App listening on port 5000');});
Step 4: Creating the .env file. We’ve to create the .env file which will contain the MY_NAME environment variable
MY_NAME=Geeksforgeeks
Project Structure: Now, we’d have the following file structure.
The file structure of the Project
Loading the Environment Variables:
Next, we’ve to import the .env package in our index.js file.
const dotenv = require('dotenv');
Now, we can configure it by setting the path to our .env file and loading the variables from it.
dotenv.config({ path: './.env' });
We can now access the environment variable in our index.js file by using the method
process.env.VARIABLE_NAME
In this case, it’ll be
process.env.MY_NAME
Final Code:
Javascript
const dotenv = require('dotenv');const express = require('express');  // Set path to .env filedotenv.config({ path: './.env' });  // Initialize appconst app = express();  // Assign routeapp.use('/', (req, res, next) => {  const name = process.env.MY_NAME;  res.status(200).json({ name });});  // Start serverapp.listen(5000, () => {  console.log('App listening on port 5000');});
Output:
"name":"Geeksforgeeks"
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?