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
- Go to Alchemy and create an account
- In the Dashboard, select Create App
- Enter a name and description, whatever you want to call it
- Select Development for Environment and Sepolia for Network
- Select Create App and select your newly-created project from the list in your Dashboard
- Select View Key
- We will need the 'HTTP' key for Step #4, so keep this tab open!
Step 2: Add HTTP URL to Local Project
- 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 the best practice, since this file may end up being pushed to Github and your endpoint is exposed.
We recommend using dotenv.
- Run
npm install dotenv
- Create a
.env
file at the root of your project - Declare a variable, you can call it whatever you want
- Copy-paste your HTTP URL from Step #1 to initialize the variable (remember to use Sepolia testnet!)
MY_ALCHEMY_RPC_ENDPOINT=https://eth-sepolia.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
.
- 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."
- You can then access the variables in your
.env
file viaprocess.env
require('@nomiclabs/hardhat-waffle');
module.exports = {
solidity: "0.8.0",
networks: {
sepolia: {
url: `${process.env.MY_ALCHEMY_RPC_ENDPOINT}`,
accounts: [`0xabc`],
}
}
};
Did you catch how we are sourcing the
url
andaccounts
variables in this file? We are loading them up fromprocess.env
using thedotenv
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. 👏💥
Updated over 1 year ago