> ## Documentation Index
> Fetch the complete documentation index at: https://goldrush.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Streaming API Authentication

> End-to-end guide for authenticating GraphQL subscriptions with the GoldRush Streaming API.

This document provides a comprehensive overview of the authentication process for GraphQL subscriptions with the Streaming API. It covers the rationale for authentication, how to obtain and use an API key, client-side implementation examples, server-side validation, error handling, and frequently asked questions.

## Why is Authentication Required?

Authentication is essential to ensure that only authorized users can access premium or rate-limited real-time data streams. **All clients must present a valid GoldRush API key to interact with the GraphQL subscription endpoints.**

## 1. Obtaining a GoldRush API Key

To begin, register for an API key at the [GoldRush Platform](https://goldrush.dev/platform/auth/register/). This key will be required for all authenticated requests to the Streaming API.

<CardGroup cols={2}>
  <Card icon="wand-magic-sparkles" title="Vibe Coders" href="https://goldrush.dev/platform/auth/register/?plan=vibe">
    \$10/mo - Built for solo builders and AI-native workflows.
  </Card>

  <Card icon="users" title="Teams" href="https://goldrush.dev/platform/auth/register/?plan=professional">
    \$250/mo - Production-grade with 50 RPS and priority support.
  </Card>
</CardGroup>

## 2. Supplying the API Key from the Client

### Use the GoldRush Client SDK (recommended)

The recommended approach is to use the official [GoldRush TypeScript Client SDK](https://www.npmjs.com/package/@covalenthq/client-sdk) which handles authentication automatically and provides a simplified interface for managing stream subscriptions.

```bash theme={null}
npm install @covalenthq/client-sdk
```

```typescript theme={null}
import {
  GoldRushClient,
  StreamingChain,
  StreamingInterval,
  StreamingTimeframe
} from "@covalenthq/client-sdk";

const client = new GoldRushClient(
  "<GOLDRUSH_API_KEY>", // Your GoldRush API key
  {},
  {
    onConnecting: () => console.log("Connecting to streaming service..."),
    onOpened: () => console.log("Connected to streaming service!"),
    onClosed: () => console.log("Disconnected from streaming service"),
    onError: (error) => console.error("Streaming error:", error),
  }
);

// Subscribe to OHLCV tokens stream
client.StreamingService.subscribeToOHLCVTokens(
  {
    chain_name: StreamingChain.BASE_MAINNET,
    token_addresses: ["0x0b3e328455c4059EEb9e3f84b5543F74E24e7E1b"],
    interval: StreamingInterval.ONE_MINUTE,
    timeframe: StreamingTimeframe.ONE_HOUR,
  },
  {
    next: (data) => {
      console.log("Received OHLCV token data:", data);
    },
    error: (error) => {
      console.error("Streaming error:", error);
    },
    complete: () => {
      console.log("Stream completed");
    },
  }
);
```

The SDK automatically handles:

* WebSocket connection management
* API key authentication
* Connection retry logic
* Error handling
* Type safety for parameters

### Use a GraphQL WebSocket Client

For direct WebSocket connections, you can use a package like [graphql-ws](https://github.com/enisdenjo/graphql-ws) library. Below is an example implementation in Node.js:

```js theme={null}
import { createClient } from "graphql-ws";

const client = createClient({
  url: "wss://streaming.goldrushdata.com/graphql",
  connectionParams: {
    GOLDRUSH_API_KEY: "<GOLDRUSH_API_KEY>", // Replace with your GoldRush API key
  },
});

(async () => {
  await client.subscribe(
    {
      query: `subscription { newPairs { ...fields } }`,
    },
    {
      next: (data) => console.log("Received data:", data),
      error: (err) => console.error("Subscription error:", err),
      complete: () => console.log("Subscription complete"),
    }
  );
})();
```

> **Note:** The API key must be provided as `GOLDRUSH_API_KEY` within the `connectionParams` object.

### Use `websocat` for Manual WebSocket Testing

For manual testing or debugging, [websocat](https://github.com/vi/websocat) can be used to interact with the WebSocket endpoint directly from the command line.

<Steps>
  <Step title="Step 1: Initiate the WebSocket Connection">
    ```
    websocat -H="Sec-WebSocket-Protocol: graphql-transport-ws" wss://streaming.goldrushdata.com/graphql
    ```
  </Step>

  <Step title="Step 2: Send the Connection Initialization Payload">
    Send the following JSON as your first message, replacing `<GOLDRUSH_API_KEY>` with your actual API key:

    ```
    {
        "type": "connection_init",
        "payload": { "GOLDRUSH_API_KEY": "<GOLDRUSH_API_KEY>" }
    }
    ```

    Wait for a `connection_ack` response from the server before proceeding.
  </Step>

  <Step title="Step 3: Submit a Subscription Query">
    You may now send a subscription query, for example:

    ```
    {
        "id": "74bb224c-22c6-4a0f-ad85-d43a8c4e49ce",
        "type": "subscribe",
        "payload": {
            "query": "subscription {newPairs(chain_name: BASE_MAINNET) { chain_name protocol protocol_version event_name tx_hash block_signed_at pair_address pair_metadata { contract_name contract_address contract_decimals contract_ticker_symbol } base_token_metadata { contract_name contract_address contract_decimals contract_ticker_symbol } quote_token_metadata { contract_name contract_address contract_decimals contract_ticker_symbol } deployer_address quote_rate quote_rate_usd liquidity market_cap supply prices { last_5m last_1hr last_6hr last_24hr } swaps { last_5m last_1hr last_6hr last_24hr }}}"
        }
    }
    ```

    If authentication is successful, you will begin receiving real-time data for your subscription.
  </Step>
</Steps>

## 3. Server-Side Authentication Process

* The server **does not** validate the API key at the time of WebSocket connection establishment.
* Instead, authentication is enforced at the start of each GraphQL subscription resolver.
* If the API key is missing or invalid, the subscription will immediately terminate with an error message.

## 4. Error Handling

If authentication fails, the client will receive a GraphQL error with one of the following codes:

* `MISSING_TOKEN`: No API key was provided in the `connection_init` payload.
* `INVALID_TOKEN`: The provided API key is malformed or invalid.
* `AUTH_SYSTEM_ERROR`: An internal server error occurred during authentication.

**Example Error Response:**

```json theme={null}
{
  "errors": [
    {
      "message": "Authentication required. Please provide a valid API key in the connection_init payload under 'GOLDRUSH_API_KEY' or 'Authorization' key.",
      "extensions": {
        "code": "MISSING_TOKEN"
      }
    }
  ]
}
```

For a complete guide to error codes, retry strategies, and debugging tips, see [Error Handling & Troubleshooting](/error-handling).

## 5. Frequently Asked Questions (FAQ)

* **What is the client experience if the key is invalid?**
  * The client will always receive a `connection_ack` response, even if the API key is invalid. Authentication errors are only reported when a subscription is initiated.
* **Where is the API key expected?**
  * The API key is expected in the `payload` of the `connection_init` message with the key `GOLDRUSH_API_KEY`.
* **What API key formats are supported?**
  * `cqt_wF[26 base58 chars]` or `cqt_rQ[26 base58 chars]`
* **Why should I use the Client SDK?**
  * The Client SDK provides automatic authentication, connection management, retry logic, type safety, and a simplified API for all streaming operations.
