Skip to content
Related Articles

Related Articles

Improve Article
How to access ExpressJS env variables in an API endpoint ?
  • Last Updated : 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:

  1. Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser.
  2. 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 app
const app = express();
  
// Assign route
app.use('/', (req, res, next) => {
  res.send('Hello World');
});
  
// Start server
app.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 file
dotenv.config({ path: './.env' });
  
// Initialize app
const app = express();
  
// Assign route
app.use('/', (req, res, next) => {
  const name = process.env.MY_NAME;
  res.status(200).json({ name });
});
  
// Start server
app.listen(5000, () => {
  console.log('App listening on port 5000');
});

Output:

"name":"Geeksforgeeks"



My Personal Notes arrow_drop_up
Recommended Articles
Page :