Set up Alchemy as Your Client

Learn how to send a blockchain request via a script using Alchemy.

👋 New to Alchemy? Get access to Alchemy for free here.

Want to integrate Alchemy into your production app?

Find out how to set up or switch your current provider to Alchemy by using the Alchemy SDK, the easiest and most powerful way to access Alchemy’s suite of Enhanced APIs and tools.

If you have an existing client, change your current node provider URL to an Alchemy URL with your API key: “https://eth-mainnet.g.alchemy.com/v2/your-api-key

Note: The scripts below need to be run in a node context or saved in a file, not run from the command line.

The Alchemy SDK

There are tons of Web3 libraries you can integrate with Alchemy. However, we recommend using the Alchemy SDK, a drop-in replacement for Ethers.js, built and configured to work seamlessly with Alchemy. This provides multiple advantages such as automatic retries and robust WebSocket support.

1. From your command line, create a new project directory and install the Alchemy SDK.

To install the Alchemy SDK, you want to create a project, and then navigate to your project directory to run the installation. Let’s go ahead and do that! Once we’re in our home directory, let’s execute the following:

With Yarn:

Yarn
$mkdir your-project-name
>cd your-project-name
>yarn init # (or yarn init --yes)
>yarn add alchemy-sdk

With NPM:

NPM
$mkdir your-project-name
>cd your-project-name
>npm init # (or npm init --yes)
>npm install alchemy-sdk

2. Create a file named index.js and add the following contents:

You should ultimately replace demo with your Alchemy HTTP API key.

index.js
1// Setup: npm install alchemy-sdk
2const { Network, Alchemy } = require("alchemy-sdk");
3
4// Optional Config object, but defaults to demo api-key and eth-mainnet.
5const settings = {
6 apiKey: "demo", // Replace with your Alchemy API Key.
7 network: Network.ETH_MAINNET, // Replace with your network.
8};
9
10const alchemy = new Alchemy(settings);
11
12async function main() {
13 const latestBlock = await alchemy.core.getBlockNumber();
14 console.log("The latest block number is", latestBlock);
15}
16
17main();

Unfamiliar with the async stuff? Check out this Medium post.

3. Run it using node

shell
$node index.js

4. You should now see the latest block number output in your console!

shell
$The latest block number is 11043912

Woo! Congrats! You just wrote your first web3 script using Alchemy and sent your first request to your Alchemy API endpoint 🎉

The app associated with your API key should now look like this on the dashboard: