JavaScript dotenv
When you create a dapp using Infura, store your environment variables on your local machine using
dotenv
to protect sensitive information, such as Infura API URLs and MetaMask mnemonics, from pushing to GitHub and becoming publicly accessible.npm i dotenv
Navigate to the project's
package.json
file to check that dotenv
is included under dependencies:
"dependencies": {
...
"dotenv": "^16.0.1",
...
You can create a
package.json
file by running a CLI questionnaire, or by creating a default package.json
file. Refer to the npm documentation for more information.At the root of your project directory, create a file named
.env
containing environment variables for sensitive information that shouldn't be shared, such as an Infura API key, Ethereum private key, or MetaMask secret recovery phrase:INFURA_API_KEY = "https://goerli.infura.io/v3/<Your-API-Key>"
MNEMONIC = "<Your-MetaMask-Secret-Recovery-Phrase>"
Never disclose your private keys or secret recovery phrases. Anyone with your private keys or secret recovery phrases can steal assets held in your account or wallet.
Give your project access to the
.env
information by including the following line at the top of your project script:require('dotenv').config();
Access the environment variables using
process.env.<Your-Environment-Variable-Name>
. For example, the following is a truffle-config.js
file for a Truffle project:require("dotenv").config();
const HDWalletProvider = require("@truffle/hdwallet-provider");
goerli: {
provider: () =>
new HDWalletProvider(
process.env.MNEMONIC,
process.env.INFURA_API_KEY
),
network_id: 4,
gas: 5500000,
confirmations: 2,
timeoutBlocks: 200,
skipDryRun: true
}
If you push your project to GitHub, the
.env
file will become publicly accessible unless you include it in a .gitignore
file.Before pushing your project, create a file named
.gitignore
, and include a line containing .env
. Your file will now be ignored by Git and won't be checked into GitHub..gitignore
ignores only untracked files. If your .env
file was committed in the past, it's now tracked by Git. Untrack the file by deleting it and running git rm --cached .env
, then include it in .gitignore
.When cloning an existing project, it might come with a
.env.sample
, .env.template
, or similar file containing environment variables without values. Copy this file into a .env
file on your local machine and fill in your values.Last modified 4mo ago