4

I am trying to read variable values from my .env file here, but all I am getting is values are undefined.

require("@nomicfoundation/hardhat-toolbox")
require('dotenv').config()

const RINKEBY_RPC_URL = process.env.RINKEBY_RPC_URL
const PRIVATE_KEY = process.env.PRIVATE_KEY

module.exports = {
  defaultNetwork: 'hardhat',
  networks: {
    rinkeby: {
      url: RINKEBY_RPC_URL,
      accounts: [PRIVATE_KEY],
      chainId: 4,
    }
  },
  solidity: "0.8.8",
};

Error:

Error HH8: There's one or more errors in your config file:

  * Invalid value undefined for HardhatConfig.networks.rinkeby.url - Expected a value of type string.
  * Invalid account: #0 for network: rinkeby - Expected string, received undefined
  
To learn more about Hardhat's configuration, please go to https://hardhat.org/config/

I have filled my .env file like this:

RINKEBY_RPC_URL=dummyUrl.com    
PRIVATE_KEY=13133private90994

I have tested my code by directly putting RPC URL and private key in my config file and it is working successfully, conforming it is an env file issue.

BTW, I'm using a Macbook pro with the new M1 Pro, maybe OS is causing this issue?

any thoughts on why this issue is occurring?

3 Answers 3

2

Import and call config() from "dotenv" on the first line in hardhat.config.js

i.e.:

// import config before anything else
import { config as dotEnvConfig } from "dotenv";
dotEnvConfig();

Explanation:

  1. I like to import config as dotEnvConfig because config might be used by another library.
  2. The function config takes an optional options object as parameter
options?: {
  path?: string; // default: `path.resolve(process.cwd(), '.env')`
  encoding?: string; // default: `utf8`
  debug?: boolean; // default: `false`
  override?: boolean; // default: `false`
}

Usually, .env file should be in the root next to your hardhat.config.js file. If not, you can define your custom path.

1

Assuming your env file is in the same directory hardhat.config.js is, you can try this:

require('dotenv').config({ path: __dirname + '/.env' }).

1
  • 1
    path is an optional parameter, and it's already defaulted to path.resolve(process.cwd(), '.env') so there's no need to define if it's returning the same value
    – BonisTech
    Commented Dec 5, 2022 at 20:36
0

Just import dotenv/config in hardhat.config file:

import { HardhatUserConfig } from "hardhat/config";
import "dotenv/config";
import "@nomicfoundation/hardhat-toolbox"; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.