Set up Alchemy with Viem

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

πŸ‘‹ Don’t have an API Key? Start here before setting up your project!

What is Viem?

Viem is a set of modules, which you can use in JavaScript or Typescript, helping you interface with Ethereum or Ethereum Virtual Machine (EVM) chains.

You will use it in this guide, configuring it with your Alchemy API URL, so you can read and write to the blockchain of your choice.

If you’re new to viem, check out our 60 minute video diving into it and the viem docs are a great place to start as well!

Let’s get started!

πŸ”§ Prerequisites

  1. Node.js

    • Required to run JavaScript/TypeScript outside the browser.
    • Install Node.js 18 or later (viem requires modern Node features).
    • Download from: https://nodejs.org/
  2. npm (comes with Node.js)

    • Default package manager bundled with Node.
    • Automatically installed when you install Node.js.
1

Project Setup and Installation

From your command line, create a new project directory and install Viem:

$# Create and enter project directory
>mkdir project && cd project
># Initialize a new Node.js project
>npm init -y
># Install viem
>npm install viem
2

Create Script

Create a file named index.js and add the following contents, replacing demo with your Alchemy API Key:

index.js
1import { createPublicClient, http } from "viem";
2import { mainnet } from "viem/chains";
3
4const client = createPublicClient({
5 chain: mainnet,
6 transport: http("https://eth-mainnet.g.alchemy.com/v2/demo"),
7});
8
9async function getLatestBlockNumber() {
10 const blockNumber = await client.getBlockNumber();
11 console.log("Latest block number:", blockNumber);
12}
13
14getLatestBlockNumber();

You can find the documentation of viem’s getBlockNumber which is configured to call out to eth_blockNumber on the Alchemy API.

3

Run It

shell
$node index.js

This should return the latest block number 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 πŸŽ‰

You can visit your request logs to see the full details of the request come through the API!

Next Steps

So, what’s next for you?

  • Want to build an application using the latest and greatest web3 login experience? Check out getting started with our wallets.
  • Need the industry best APIs to access blockchain data (tokens, transfers, nfts, prices and more)? Jump on over to our data APIs.
  • Want to find all the methods available to you on our node API? Check out the documentation here.
  • Need to learn more about crypto? We’ve got you covered at Alchemy University.