Authentication overview
Alchemy Ethereum provides infrastructure for Web3 application development, offering access to Ethereum and other blockchain networks. Authentication for Alchemy's services primarily relies on API keys. These keys serve as a unique identifier for your application, allowing Alchemy to track usage, apply rate limits, and enforce access policies. API keys are essential for interacting with the Alchemy Supernode and other enhanced APIs.
When making requests to Alchemy's endpoints, your API key is typically embedded directly into the request URL. This method simplifies integration for many client-side and server-side applications, particularly within the Web3 ecosystem where direct RPC calls are common. While convenient, this approach necessitates careful management of API keys to prevent unauthorized access and potential misuse of your account's compute unit allocation.
Beyond basic API key access, Alchemy offers additional security features such as IP address whitelisting and referrer whitelisting to restrict where your API key can be used. These mechanisms enhance the security posture of applications by adding layers of verification beyond just possessing the correct key.
Supported authentication methods
Alchemy Ethereum primarily supports API key authentication. This method is standard for accessing its various services, including the Supernode, NFT API, and Enhanced APIs. The table below outlines the primary authentication method and its typical use cases and security considerations.
| Method | When to Use | Security Level |
|---|---|---|
| API Key (URL Parameter) |
|
|
While API keys are the primary method, the availability of features like IP and referrer whitelisting allows developers to implement more granular access controls. This aligns with general security practices for API access, where restricting the origin of requests adds a significant layer of protection against unauthorized use, even if an API key is compromised. The OAuth 2.0 framework, for example, emphasizes token-based authentication and delegation, but for direct API access to infrastructure providers like Alchemy, API keys remain a common and effective approach when managed securely.
Getting your credentials
To obtain your Alchemy API key, you must first create an account and project on the Alchemy platform. The process involves several steps within the Alchemy dashboard:
- Create an Alchemy Account: Navigate to the Alchemy homepage and sign up for a new account. You can utilize the free 'Growth' tier, which provides access for up to 50 million compute units per month.
- Create a New Project: Once logged in, go to your dashboard. Click on the "Create New App" or "Create New Project" button. You will be prompted to select a chain (e.g., Ethereum) and a network (e.g., Mainnet, Sepolia, Goerli).
- Retrieve Your API Key: After creating your project, Alchemy will automatically generate an API key for it. You can find this key listed under your project details in the dashboard. It is typically labeled as "API Key" or "HTTP API Key."
- Configure Security Settings (Optional but Recommended): Within your project settings, you can configure additional security measures such as IP whitelisting or referrer whitelisting. This allows you to specify which IP addresses or website domains are permitted to use your API key, significantly reducing the risk of unauthorized access.
Each project you create on Alchemy will have its own unique API key. It is a best practice to create separate projects and API keys for different applications or environments (e.g., development, staging, production) to isolate access and simplify key rotation or revocation if necessary.
Authenticated request example
Alchemy API keys are typically included directly in the URL when making an RPC call. The following examples demonstrate how to make an authenticated request using your Alchemy API key in both a direct curl command and JavaScript, a common language for Web3 development.
cURL Example
This curl command makes a request to the Ethereum Mainnet to get the latest block number, replacing YOUR_ALCHEMY_API_KEY with your actual key.
curl https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_API_KEY \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
JavaScript Example (using fetch)
This JavaScript example demonstrates how to perform a similar request using the fetch API, suitable for browser or Node.js environments. Note that for client-side applications, it's crucial to implement referrer whitelisting or use a secure backend proxy to prevent API key exposure.
const ALCHEMY_API_KEY = "YOUR_ALCHEMY_API_KEY";
const ALCHEMY_URL = `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_API_KEY}`;
async function getBlockNumber() {
try {
const response = await fetch(ALCHEMY_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_blockNumber',
params: [],
id: 1,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Latest block number:', parseInt(data.result, 16));
} catch (error) {
console.error('Error fetching block number:', error);
}
}
getBlockNumber();
Using Alchemy SDK
For more robust and idiomatic integration, Alchemy provides official SDKs for JavaScript, Python, Go, and TypeScript. These SDKs abstract away the direct HTTP request details and handle API key integration seamlessly. Here's a JavaScript example using the Alchemy SDK:
import { Alchemy, Network } from "alchemy-sdk";
const settings = {
apiKey: "YOUR_ALCHEMY_API_KEY", // Replace with your Alchemy API Key.
network: Network.ETH_MAINNET, // Replace with your network.
};
const alchemy = new Alchemy(settings);
async function getBlockNumberSDK() {
try {
const blockNumber = await alchemy.core.getBlockNumber();
console.log("Latest block number (SDK):", blockNumber);
} catch (error) {
console.error("Error fetching block number with SDK:", error);
}
}
getBlockNumberSDK();
Using the SDKs is generally recommended as they simplify error handling, provide type safety (especially in TypeScript), and are maintained by Alchemy, ensuring compatibility with their latest API features.
Security best practices
Secure management of API keys is critical to protect your Alchemy account from unauthorized usage and potential service disruptions. Adhering to these best practices can significantly enhance the security of your applications:
- Never Hardcode API Keys in Client-Side Code: Exposing API keys directly in frontend JavaScript or mobile applications allows anyone to view and potentially misuse them. If your application requires client-side access, consider using a backend proxy to funnel requests or implement strict referrer whitelisting.
- Use Environment Variables: For server-side applications, store your API keys in environment variables (e.g.,
.envfiles for local development, or platform-specific environment settings for cloud deployments). This keeps keys out of your codebase and version control systems. - Implement IP Whitelisting: Configure your Alchemy project to only accept requests originating from a specific set of IP addresses. This is highly effective for backend services with static IP addresses. Even if your key is compromised, it cannot be used from an unauthorized IP.
- Utilize Referrer Whitelisting: For web applications that make direct client-side calls to Alchemy, set up referrer whitelisting. This restricts API key usage to requests coming from specified domain names, such as your application's URL.
- Regularly Rotate API Keys: Periodically generate new API keys and deprecate old ones. This practice reduces the window of opportunity for a compromised key to be exploited. Many security frameworks, such as those recommended by Google Cloud for API key security, suggest regular rotation.
- Create Separate Keys for Different Environments/Applications: Use distinct API keys for development, staging, and production environments, as well as for different applications or projects. This allows for granular control and easier revocation if one key is compromised without affecting others.
- Monitor Usage and Set Alerts: Regularly review your Alchemy dashboard for unusual API usage patterns. Set up alerts for unexpected spikes in compute units consumed, which could indicate unauthorized activity.
- Avoid Committing Keys to Version Control: Ensure your
.gitignorefile is configured to exclude any files containing API keys (e.g.,.envfiles) to prevent accidental exposure in public or private repositories. - Use a Backend Proxy for Client-Side Calls: If your frontend application needs to interact with Alchemy, consider routing requests through a secure backend proxy. The proxy can then add the API key securely before forwarding the request to Alchemy, shielding the key from client-side exposure.
By implementing these security measures, developers can significantly mitigate the risks associated with API key exposure and maintain the integrity and security of their Web3 applications built on Alchemy Ethereum.