> For the complete documentation index, see [llms.txt](https://docs.rpcfast.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rpcfast.com/rpc-fast-saas-solana/solana-rpc-methods/connecting-to-solana-rpc.md).

# Connecting to Solana RPC

Connect to RPC Fast Solana RPC over HTTPS and WebSocket, authenticate with your API key, and send your first requests from Rust, Python, or TypeScript.

Your account in the [Solana dashboard](https://rpcfast.com/) can have multiple **projects**, for example one per application or environment. Each project has its own **API key**, ready-to-use HTTPS and WebSocket endpoints, and access settings, all shown on the project page. The maximum number of projects depends on your plan; see [Pricing and Plans](https://docs.rpcfast.com/rpc-fast-saas-solana/pricing-and-plans.md). See [Getting Started](https://docs.rpcfast.com/rpc-fast-saas-solana/getting-started.md) if you don't have a project yet.

{% hint style="warning" %}
Keep your API key secret. Anyone who has it can send requests on your behalf and consume your plan limits.
{% endhint %}

## Endpoints

| Network | Location           | HTTPS (JSON-RPC)                                    | WebSocket (PubSub)                                |
| ------- | ------------------ | --------------------------------------------------- | ------------------------------------------------- |
| Mainnet | Frankfurt, Germany | `https://solana-rpc.rpcfast.com/?api_key=<API_KEY>` | `wss://solana-rpc.rpcfast.com/?api_key=<API_KEY>` |

RPC nodes are hosted in Frankfurt, in the **Equinix FR13** data center. For the lowest latency, deploy your application in the same data center or nearby.

HTTP requests are standard Solana JSON-RPC 2.0 `POST` requests, and WebSocket connections speak standard Solana PubSub, so any Solana SDK works without changes. See [Solana RPC](https://docs.rpcfast.com/rpc-fast-saas-solana/solana-rpc-methods.md) for the supported methods.

## Authentication

RPC Fast authenticates every HTTP request and every WebSocket connection with your API key. There are two ways to pass it.

### `api_key` query parameter (primary)

Append the key to the endpoint URL. This is the primary method: it is the format shown in the dashboard, and it works with every client, including WebSocket connections opened from a browser.

```bash
curl https://solana-rpc.rpcfast.com/?api_key=<API_KEY> \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment":"confirmed"}]}'
```

### `X-Token` header (alternative)

Send the key in the `X-Token` HTTP header and use the endpoint URL without the query parameter. This keeps the key out of URLs, for example in logs of proxies you operate. It works with any client that can set custom headers, including WebSocket clients outside the browser (browser WebSocket APIs cannot set custom headers).

```bash
curl https://solana-rpc.rpcfast.com \
  -H 'X-Token: <API_KEY>' \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment":"confirmed"}]}'
```

{% hint style="info" %}
If a request carries both, the `api_key` query parameter takes precedence and the `X-Token` header is ignored.
{% endhint %}

### Authentication errors

| HTTP status | JSON-RPC error                         | Cause                                                                                 |
| ----------- | -------------------------------------- | ------------------------------------------------------------------------------------- |
| `401`       | `-32000` `API key is required`         | Neither the `api_key` query parameter nor the `X-Token` header was sent.              |
| `401`       | `-32000` `Provided API key is invalid` | The key is unknown, revoked, or not enabled for this product.                         |
| `403`       | `-32007` `IP address not allowed`      | The project has a **Network access** allowlist and the client IP is not on it.        |
| `403`       | `-32600` `Origin not allowed`          | The project has a **Browser access** allowlist and the browser `Origin` is not on it. |

WebSocket connections are authenticated during the handshake; a rejected connection fails with the same HTTP status before any subscription is created.

You can restrict where your key may be used in the project **Settings** in the dashboard: **Network access** limits requests to listed IP addresses or CIDR ranges, and **Browser access** limits browser requests to listed origins.

## Examples

The examples below read the key from the `RPCFAST_API_KEY` environment variable and fetch the current slot.

### HTTP requests

{% tabs %}
{% tab title="Rust" %}
`Cargo.toml`:

```toml
[dependencies]
solana-client = "3.1"
solana-commitment-config = "3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

```rust
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("RPCFAST_API_KEY")?;
    let url = format!("https://solana-rpc.rpcfast.com/?api_key={api_key}");

    let client = RpcClient::new_with_commitment(url, CommitmentConfig::confirmed());
    let slot = client.get_slot().await?;
    println!("Current slot: {slot}");
    Ok(())
}
```

To authenticate with the `X-Token` header instead, build the client from a `reqwest` client with a default header (add `solana-rpc-client = "3.1"` and `reqwest = "0.12"`):

```rust
use reqwest::header::{HeaderMap, HeaderValue};
use solana_commitment_config::CommitmentConfig;
use solana_rpc_client::{
    http_sender::HttpSender, nonblocking::rpc_client::RpcClient, rpc_client::RpcClientConfig,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("RPCFAST_API_KEY")?;

    let mut headers = HeaderMap::new();
    headers.insert("x-token", HeaderValue::from_str(&api_key)?);
    let http = reqwest::Client::builder().default_headers(headers).build()?;

    let sender = HttpSender::new_with_client("https://solana-rpc.rpcfast.com", http);
    let config = RpcClientConfig::with_commitment(CommitmentConfig::confirmed());
    let client = RpcClient::new_sender(sender, config);

    let slot = client.get_slot().await?;
    println!("Current slot: {slot}");
    Ok(())
}
```

{% endtab %}

{% tab title="Python" %}

```bash
pip install solana
```

```python
import asyncio
import os

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed

API_KEY = os.environ["RPCFAST_API_KEY"]


async def main() -> None:
    # Primary: API key in the query string
    async with AsyncClient(
        f"https://solana-rpc.rpcfast.com/?api_key={API_KEY}", commitment=Confirmed
    ) as client:
        print("Current slot:", (await client.get_slot()).value)

    # Alternative: API key in the X-Token header
    async with AsyncClient(
        "https://solana-rpc.rpcfast.com",
        commitment=Confirmed,
        extra_headers={"X-Token": API_KEY},
    ) as client:
        print("Current slot:", (await client.get_slot()).value)


asyncio.run(main())
```

Without an SDK, send a plain JSON-RPC request:

```python
import os

import requests

response = requests.post(
    "https://solana-rpc.rpcfast.com",
    params={"api_key": os.environ["RPCFAST_API_KEY"]},
    json={"jsonrpc": "2.0", "id": 1, "method": "getSlot", "params": [{"commitment": "confirmed"}]},
    timeout=10,
)
print(response.json())
```

{% endtab %}

{% tab title="TypeScript" %}

```bash
npm install @solana/kit
```

```typescript
import { createSolanaRpc } from '@solana/kit';

const apiKey = process.env.RPCFAST_API_KEY!;

// Primary: API key in the query string
const rpc = createSolanaRpc(`https://solana-rpc.rpcfast.com/?api_key=${apiKey}`);
console.log('Current slot:', await rpc.getSlot({ commitment: 'confirmed' }).send());

// Alternative: API key in the X-Token header
const rpcWithHeader = createSolanaRpc('https://solana-rpc.rpcfast.com', {
  headers: { 'x-token': apiKey },
});
console.log('Current slot:', await rpcWithHeader.getSlot({ commitment: 'confirmed' }).send());
```

With the `Connection` class from `@solana/web3.js`:

```typescript
import { Connection } from '@solana/web3.js';

const apiKey = process.env.RPCFAST_API_KEY!;

// Primary: API key in the query string
const connection = new Connection(`https://solana-rpc.rpcfast.com/?api_key=${apiKey}`, 'confirmed');
console.log('Current slot:', await connection.getSlot());

// Alternative: API key in the X-Token header
const connectionWithHeader = new Connection('https://solana-rpc.rpcfast.com', {
  commitment: 'confirmed',
  httpHeaders: { 'x-token': apiKey },
});
console.log('Current slot:', await connectionWithHeader.getSlot());
```

{% endtab %}
{% endtabs %}

### WebSocket subscriptions

Each example subscribes to slot updates, prints five slots, and exits.

{% tabs %}
{% tab title="Rust" %}
`Cargo.toml`:

```toml
[dependencies]
solana-client = "3.1"
futures-util = "0.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

```rust
use futures_util::StreamExt;
use solana_client::nonblocking::pubsub_client::PubsubClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("RPCFAST_API_KEY")?;
    let url = format!("wss://solana-rpc.rpcfast.com/?api_key={api_key}");

    let client = PubsubClient::new(&url).await?;
    let (mut slots, unsubscribe) = client.slot_subscribe().await?;
    for _ in 0..5 {
        if let Some(info) = slots.next().await {
            println!("Slot: {}", info.slot);
        }
    }
    unsubscribe().await;
    Ok(())
}
```

{% endtab %}

{% tab title="Python" %}

```bash
pip install websockets
```

```python
import asyncio
import json
import os

import websockets


async def main() -> None:
    url = f"wss://solana-rpc.rpcfast.com/?api_key={os.environ['RPCFAST_API_KEY']}"
    async with websockets.connect(url) as ws:
        await ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "slotSubscribe"}))
        print("Subscription:", json.loads(await ws.recv()))
        for _ in range(5):
            message = json.loads(await ws.recv())
            print("Slot:", message["params"]["result"]["slot"])


asyncio.run(main())
```

To use the `X-Token` header, pass `additional_headers={"X-Token": API_KEY}` to `websockets.connect` and drop the query parameter.
{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { createSolanaRpcSubscriptions } from '@solana/kit';

const apiKey = process.env.RPCFAST_API_KEY!;
const rpcSubscriptions = createSolanaRpcSubscriptions(
  `wss://solana-rpc.rpcfast.com/?api_key=${apiKey}`,
);

const abortController = new AbortController();
const slots = await rpcSubscriptions
  .slotNotifications()
  .subscribe({ abortSignal: abortController.signal });

let received = 0;
for await (const { slot } of slots) {
  console.log('Slot:', slot);
  if (++received === 5) abortController.abort();
}
```

{% endtab %}
{% endtabs %}

{% hint style="success" icon="child-reaching" %}
For presale or technical questions, [contact us on Telegram](https://telegram.me/+SpMbJTPTakAxNjdi). Our team will reply in the community chat. Please be aware of impersonators.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.rpcfast.com/rpc-fast-saas-solana/solana-rpc-methods/connecting-to-solana-rpc.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
