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

# Authentication

> Learn how to authenticate with the CoinStats API

<Tip>
  Building an AI agent and want to skip the sign-up? See
  [x402 Pay-Per-Request](/ai-agents/x402) — no account, no API key, just a
  Base wallet with USDC.
</Tip>

The CoinStats API uses API key authentication for all requests.

Follow these steps to get started:

<Steps>
  <Step title="Sign up or log in to CoinStats">
    Visit the [CoinStats API dashboard](https://openapi.coinstats.app) and create an account or log in to your existing one.
  </Step>

  <Step title="Generate your API key">
    After signing in, go to your dashboard and generate a new API key. This key will be used to authenticate your requests.
  </Step>

  <Step title="Use the API key in requests">
    Add the API key to the `X-API-KEY` header in every request you make.

    ```bash theme={null}
    curl -H "X-API-KEY: your-api-key" \
         https://api.coinstats.app/v1/coins
    ```
  </Step>

  <Step title="Example: JavaScript (Fetch)">
    ```javascript theme={null}
    const response = await fetch('https://api.coinstats.app/v1/coins', {
      headers: {
        'X-API-KEY': 'your-api-key'
      }
    });
    const data = await response.json();
    ```
  </Step>

  <Step title="Secure your API key">
    <Warning>
      **API Key Security Alert**: Exposed API keys can lead to unauthorized usage, quota exhaustion, and unexpected charges. Always protect your keys in production applications.
    </Warning>

    ## Why Key Protection Matters

    When you expose API keys on the client side, malicious actors can discover and abuse them, potentially:

    <CardGroup cols={2}>
      <Card title="Exhaust Your Quota" icon="gauge-high">
        Malicious usage can quickly consume your API limits and cause service interruptions
      </Card>

      <Card title="Increase Your Bills" icon="credit-card">
        Unauthorized requests can push you over plan limits and trigger unexpected charges
      </Card>
    </CardGroup>

    ## Essential Security Practices

    <Tabs>
      <Tab title="Environment Variables">
        Never hardcode API keys in your source code. Use environment variables instead.

        ```javascript theme={null}
        // ❌ Don't do this
        const apiKey = "your-api-key-here";

        // ✅ Do this instead
        const apiKey = process.env.COINSTATS_API_KEY;
        ```

        ```bash theme={null}
        # .env file
        COINSTATS_API_KEY=your-actual-api-key
        ```
      </Tab>

      <Tab title="Frontend Security">
        **Never expose API keys in frontend code.** Use these approaches instead:

        <AccordionGroup>
          <Accordion title="Backend Proxy (Recommended)">
            Create a backend endpoint that forwards requests to CoinStats:

            ```javascript theme={null}
            // Backend endpoint
            app.get('/api/coins', async (req, res) => {
              const response = await fetch('https://api.coinstats.app/v1/coins', {
                headers: {
                  'X-API-KEY': process.env.COINSTATS_API_KEY
                }
              });
              const data = await response.json();
              res.json(data);
            });

            // Frontend code (no API key needed)
            const response = await fetch('/api/coins');
            const data = await response.json();
            ```
          </Accordion>

          <Accordion title="Server-Side Rendering">
            Fetch data server-side and pass it to your frontend:

            ```javascript theme={null}
            // Next.js example
            export async function getServerSideProps() {
              const response = await fetch('https://api.coinstats.app/v1/coins', {
                headers: {
                  'X-API-KEY': process.env.COINSTATS_API_KEY
                }
              });
              const data = await response.json();
              
              return { props: { coins: data } };
            }
            ```
          </Accordion>
        </AccordionGroup>
      </Tab>

      <Tab title="Key Management">
        <CardGroup cols={1}>
          <Card title="Separate Keys for Environments" icon="layers">
            Use different API keys for development, staging, and production:

            ```javascript theme={null}
            const getApiKey = () => {
              switch (process.env.NODE_ENV) {
                case 'production':
                  return process.env.COINSTATS_API_KEY_PROD;
                case 'staging':
                  return process.env.COINSTATS_API_KEY_STAGING;
                default:
                  return process.env.COINSTATS_API_KEY_DEV;
              }
            };
            ```
          </Card>

          <Card title="Regular Key Rotation" icon="arrows-rotate">
            <Steps>
              <Step title="Generate New Key">
                Create a new API key in your CoinStats dashboard
              </Step>

              <Step title="Update Applications">
                Update all applications to use the new key
              </Step>

              <Step title="Test Thoroughly">
                Ensure all services work with the new key
              </Step>

              <Step title="Revoke Old Key">
                Delete the old key from your dashboard
              </Step>
            </Steps>
          </Card>
        </CardGroup>
      </Tab>
    </Tabs>

    ## Security Checklist

    <AccordionGroup>
      <Accordion title="✅ Development Security">
        * [ ] Use environment variables for API keys
        * [ ] Never commit API keys to version control
        * [ ] Add `.env` to `.gitignore`
        * [ ] Use different keys for different environments
      </Accordion>

      <Accordion title="✅ Production Security">
        * [ ] Keep API keys server-side only
        * [ ] Monitor API usage regularly in dashboard
        * [ ] Set up usage alerts
        * [ ] Rotate keys regularly
        * [ ] Document security procedures for your team
      </Accordion>
    </AccordionGroup>

    <Note>
      **Monitor Usage**: Regularly check your API usage in the CoinStats dashboard for unusual patterns like sudden spikes, requests from unexpected locations, or usage during off-hours.
    </Note>
  </Step>

  <Step title="Handle authentication errors">
    If your API key is missing or incorrect, you'll receive a `401 Unauthorized` response:

    ```json theme={null}
    {
      "error": "Unauthorized",
      "message": "Invalid API key"
    }
    ```
  </Step>
</Steps>
