I just installed browserify on my system and am able to bundle my scripts but when I call my env variables I am getting undefined
.
My file structure:
MyProject
dist
node_modules
src
index.html
index.js
bundle.js
.env
package-lock.json
package.json
yarn.lock
index.html
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<div class="d-flex align-items-center justify-content-center" id="record">
<div class="input-group mb-3 input-group-lg w-50">
<input type="text" class="form-control" id="rec-id" placeholder="Enter ID">
<button class="btn btn-success" id="mybtn" type="button">Enter</button>
</div>
</div>
<div class="d-flex align-items-center justify-content-center d-none" id="show-alert">
<div class="alert alert-danger alert-dismissible fade show row">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<strong>Danger!</strong> Button was clicked
</div>
</div>
<script src="bundle.js"></script>
index.js
require("dotenv").config();
console.log(process.env.MY_TOKEN);
Successfully ran browserify src/index.js -o src/bundle.js
.env
MY_TOKEN=qwer123456
When I run my code, I am getting undefined
in my console instead of qwer123456
.
2
Answers
You can’t do that.
Webpack (which does a similar job to Browserify) has a plugin that can expose dotenv data to bundled code. However, you do not want to do that.
You said, in a comment:
A .env file serves two purposes:
It does not, and cannot, hide a value from the environment that needs to use it.
For your client-side JavaScript to access your Slack auth token, you have to give the Slack auth token to the browser. The browser is completely under the control of the user. If you do that then the user can read the auth token and do anything with the Slack API they like with that authorisation.
To keep the tokens secret you need to use them in server-side code and expose any (limited) functionality the client should have over an API (e.g. one that can be accessed via Ajax) which you should probably secure with your own AuthN/AuthZ.
Try to parse content of the
.env
file by usingdotenv.parse()
: