How to Add Alchemy RPC Endpoint for Local Development

Use dotenv to set an environment-wide variable containing your Alchemy RPC HTTP endpoint.

Step 1: Create an Alchemy Account

  1. Go to Alchemy and create an account
  2. In the Dashboard, select 'Create App'
  3. Enter a name and description, whatever you want to call it
  4. Select 'Development' for Environment and 'Göerli' for Network
  5. Select 'Create App' and select your newly-created project from the list in your Dashboard

Alchemy

  1. Select 'View Key'
  2. We will need the 'HTTP' key for Step #4, so keep this tab open!

Step 2: Add HTTP URL to Local Project

  1. Select 'Create a basic sample project'

If you are using Hardhat, you can choose to copy-paste your HTTP endpoint directly into the networks.url key. Hardcoding the endpoint is not best practice, since this file may end up being pushed to Github and your endpoint is exposed.

We recommend using dotenv.

  1. Run npm install dotenv
  2. Create a .env file at the root of your project
  3. Declare a variable, you can call it whatever you want
  4. Copy-paste your HTTP URL from Step #1 to initialize the variable (remember to use Goerli testnet!)
MY_ALCHEMY_RPC_ENDPOINT=https://eth-goerli.g.alchemy.com/v2/[YOUR-API-KEY]
MY_PRIVATE_KEY=0x123

This is the perfect place to use sensitive data like private keys! Always make sure to only use test keys and include .env file in .gitignore.

  1. In your hardhat.config.js, copy-paste this line at the top of the file:
require('dotenv').config();

This basically loads in all the environment-wide variables declared in your .env and bring them into your config file. In other words, pasting this line makes your config file go "Ok, this person is telling me to load the variables in the root's .env file to this file."

  1. You can then access the variables in your .env file via process.env
require('@nomiclabs/hardhat-waffle');


module.exports = {
  solidity: "0.8.0",
  networks: {
    goerli: {
      url: `${process.env.MY_ALCHEMY_RPC_ENDPOINT}`,
      accounts: [`0xabc`],
    } 
  }
};

Did you catch how we are sourcing the url and accounts variables in this file? We are loading them up from process.env using the dotenv library we installed at the beginning of this step. This functionality allows us to have project-wide environment variables without having to explicitly define them in every file needed.

Any file that has the

require('dotenv').config();

statement at the top will automatically load any variables in the root's .env file.

Step 3: Build!

Now that you've loaded up an Alchemy RPC endpoint to your local development project, any programs run with npx hardhat will use the Alchemy endpoint in your dashboard. 👏💥