Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my JavaScript fetch function. Everything is functioning correctly, but the issue is that my token and session id are appearing in the code.

var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Authorization", "Token <mytoken>");
    myHeaders.append("Cookie", "sessionid= <mysessionid>");
    myHeaders.append("User-Agent", "Mozilla/5.0");
   

I am wondering how I can securely store these sensitive values in a .env file for better security.

Thank you!

Answer №1

If you're looking for a solution without the need to install additional packages, I have one!

You can find my original response here, but I'll share it here as well.

I managed to develop a viable solution by referring to this informative article. Feel free to customize the steps below according to your variables and dive into the article for a comprehensive understanding.

Note: This approach is suitable for small personal projects where data confidentiality is not critical, but it's best avoided in larger projects that demand robust security measures.

In case your project is hosted on platforms like Netlify with build/deploy capabilities:

  1. Navigate to the build settings
  2. If your script file resides in a directory, specify the build command as follows:
    cd DIRECTORY-FOR-THE-SCRIPT-FILE && echo -e "export const USERNAME="123";\nexport const PASSWORD="password";" > config.js
  3. For scripts in the root folder, set the command to:
    echo -e "export const USERNAME="123";\nexport const PASSWORD="password"; > config.js
  4. In your index.html file where the script is imported, ensure your script tag includes this attribute: type="module" e.g.,
    <script src="./index.js" type="module"></script>
  5. To access the variables in your script file, add this line:
    import {USERNAME, PASSWORD} from "./config.js"
  6. Manually trigger a redeploy on Netlify or let automatic deploys take over if already enabled for the repository.
  7. That's all there is to it!

This method resolved my issue and hopefully benefits others too✨.

Answer №2

Start by installing the dotenv npm package

You can do this in your terminal:

npm install dotenv

If you're working with vanilla JavaScript that doesn't support require, consider installing the requirejs npm package

This is how you can do it in your terminal:

npm install requirejs

Once installed, you can implement require in vanilla JavaScript using the following code:

var requirejs = require('requirejs');

requirejs.config({
    // Top-level main.js/index.js require function
   // to load node modules relative to the top-level JS file  
    nodeRequire: require
});

requirejs(['foo', 'bar'],
function (foo, bar) {
    // foo and bar are loaded as per requirejs config,
   // but if not found, then node's require is used
   // to load the module 
});

For further information on requirejs, refer to their documentation here.

You can now incorporate environment variables into your vanilla JavaScript.

To learn more about this, visit this link.

Answer №3

Utilizing environment variables in the backend of an application is crucial. While some may argue that a .env file can be created within a React app, it's important to note that React comes bundled with Node.js. Therefore, npm must be used for specific tasks.

In VanillaJS, you can also generate a .env file; however, the process.env global variable provided by Node won't be accessible during runtime. Node interprets the .env file as an object, enabling access through process.env.env_variable.

const env = {
    env_variable: "bgrtyaqQtyfadV0F08BHGvfsgskl",
    topic_id: "F08BHGvfsgsklgrtyaqQtyfadV0F08"
}

console.log(process.env.env_variable)

// prints bgrtyaqQtyfadV0F08BHGvfsgskl to the console

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

What steps can be taken to resolve the error "Incompatible types: TodoItem undefined cannot be assigned to type TodoItem"?

I am currently in the process of learning TypeScript. Here is what's inside todoItem.ts: export class TodoItem { constructor( public id: number, public task: string, public complete: boolean = false ) {} printDetails(): void { ...

Setting the current time in an Animation using ThreeJS

I'm utilizing skinning and skeletal animation within ThreeJS. My goal is to navigate through an animation by moving backward and forward, as well as jumping to specific locations within the sequence instead of the usual looping behavior. The animatio ...

What is the best way to choose an item from a dropdown menu using JavaScript?

Is there a way to set the dropdown value from the client side? Currently, I am loading countries and states using a countries.js file on grid row selection for updating. However, because it is loaded from the client side, I am unable to load country and st ...

The challenge of default Vuetify styles within a Nuxt environment

Here is my code snippet: <div class="cd-page__details-wrapper"> <v-text-field label="Outlined" placeholder="Outlined" outlined ></v-text-field> </div> Unfortunately, something unexpecte ...

How to adjust transparency in Three.js objects

Currently, I am developing a scene where certain elements are loaded from a JSON file. While I am able to toggle the visibility of each individual object, I now find myself wanting to adjust the opacity/transparency of an individual object. The objects in ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

A guide on linking an object in strapi V4 to a React app

Recently in strapi v4, there was a change in the response API structure from an array to an object. When analyzing the response using Postman on my local strapi API and converting it into raw format with stringify, I noticed that the API response consists ...

The layout of the keyboard in Cordova has been altered

Just starting out with my first Cordova app and I'm working on a simple login form. The issue I'm facing is that whenever I click on an input element, the keyboard pops up and completely messes up my layout, which should be straightforward. Has ...

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

What is the best method for utilizing the jQuery Selector in this particular web application?

I have been attempting to figure out how to select a delete icon within my personal web application. delectIcon HTML <main> <div class="container"> <div class="tabs"> <a href=""><p><span class="act ...

What is the best approach to retain a user's selection for dark mode?

I have created a small website to showcase my work, but I'm struggling to figure out how to make the website remember a user's choice of dark mode. After searching on Stack Overflow, I came across suggestions like using cookies or localStorage. ...

Utilizing a variable within an Angular filter: A step-by-step guide

Currently, I am in the process of experimenting with Angular. I am able to retrieve some data from the controller and successfully apply a filter when passing it as a string. However, I encounter issues when attempting to use a variable for the filter inst ...

Error encountered while deploying to Heroku: cross-env not detected in Node.js application

As I attempt to deploy my project on Heroku, the following error persists despite all my efforts. Please assist me in resolving this issue: { "name": "storybooks", "version": "1.0.0", "des ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Triggering a Bootstrap 5 dropdown through code is only effective within the browser's developer console, rather than standard JavaScript implementation

I attempted to display a Bootstrap5 dropdown by clicking on a link in my web application. Despite trying various methods, such as dispatching events and utilizing the bootstrap Dropdown classes, I was unable to achieve success. Interestingly, both approach ...

Employing angularjs alongside a static jsonp file produces results on the first attempt

Currently, I have data being retrieved from a jsonp file within my application. worm.factory('simpleFactory', function ($http, gf) { var simpleFactory = ""; return { getJson: function ($scope) { var url = 'myfile.json?callback=J ...

"Effortlessly search and replace text with a click of a button using jQuery - A beginner

Is there a way to implement a search and replace function for text on button click using jQuery or JavaScript? For example, in Visual Studio, pressing ctrl + f opens a box that allows for text replacement. Is it possible to achieve the same functionality ...

Tips for placing <div .right> above <div .left> when the window is small, given that <div .right> is positioned to the right of <div .left> when the window is large

I've come across a similar layout before, but I'm struggling to replicate it myself. The idea is to have text aligned on the left side with an image floated to the right. Instead of the image appearing below the text when the window size is red ...

What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined? Or is there a method to achieve this in Express? Express router.put('/edit/:id', function(req, res) { Person.findOneAndUpdate({ _id: req.p ...