This tutorial uses the getBlockNumber endpoint.
This guide assumes you've gone through the getting started steps and have an Alchemy account!
mkdir web3-example
cd web3-exampleYou can use any web3 library of your choosing. We recommend Viem for new projects, or Ethers.js if you're already familiar with it.
npm install viemimport { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
// Replace with your Alchemy API Key
const apiKey = "demo"; // Replace with your Alchemy API Key.
const publicClient = createPublicClient({
chain: mainnet,
transport: http(`https://eth-mainnet.g.alchemy.com/v2/${apiKey}`)
})
async function main() {
try {
const latestBlock = await publicClient.getBlockNumber();
console.log("The latest block number is", latestBlock);
} catch (error) {
console.error('Request failed:', error.message);
}
}
main();You should ultimately replace demo with your Alchemy HTTP API key.
Unfamiliar with the async stuff? Check out this Medium post.
node index.js- You should now see the latest block number output in your console!
The latest block number is 11043912Woo! Congrats! You just wrote your first web3 script using Alchemy ๐
Once you complete this tutorial, let us know how your experience was or if you have any feedback by tagging us on Twitter @Alchemy!
Not sure what to do next? Build upon your skills learned in this tutorial by checking out our beginner's tutorial for sending Ethereum transactions using Web3 and Alchemy.