Client-Side Usage

Use origin-restricted API keys safely in browser JavaScript.

You can call the TrustTrade API directly from browser JavaScript using origin-restricted keys. These keys are safe to embed in client-side code because they only work from specified domains.

Create an origin-restricted key

First, create a key with allowed_origins set:

curl -X POST https://api.trusttrade.com/v1/account/keys \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "allowed_origins": ["https://your-site.com", "https://staging.your-site.com"],
    "label": "Client-side key"
  }'

How origin restriction works

When a key has allowed_origins:

  1. The API checks the Origin header against the allowed list
  2. Requests without an Origin header are rejected (403)
  3. Per-IP rate limiting is enforced (60 requests/min per client IP)
  4. The per-key rate limit still applies (10 requests/min total)

Browser example

const API_KEY = 'your_origin_restricted_key';
const BASE_URL = 'https://api.trusttrade.com/v1';

async function getDeviceValue(deviceId) {
  const response = await fetch(`${BASE_URL}/devices/${deviceId}`, {
    headers: { 'X-API-Key': API_KEY },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }

  return response.json();
}

// Usage
const valuation = await getDeviceValue('MBA-M2-256-8GB');
console.log(`Good condition: $${valuation.currentValuation.good}`);

React example

import { useState } from 'react';

const API_KEY = process.env.NEXT_PUBLIC_TRUSTTRADE_API_KEY;

function DeviceLookup() {
  const [device, setDevice] = useState(null);
  const [loading, setLoading] = useState(false);

  async function handleLookup(deviceId: string) {
    setLoading(true);
    try {
      const res = await fetch(
        `https://api.trusttrade.com/v1/devices/${deviceId}`,
        { headers: { 'X-API-Key': API_KEY } }
      );
      setDevice(await res.json());
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <button onClick={() => handleLookup('MBA-M2-256-8GB')}>
        {loading ? 'Loading...' : 'Get Valuation'}
      </button>
      {device && (
        <p>Good condition: ${device.currentValuation.good}</p>
      )}
    </div>
  );
}

Security considerations

  • Origin-restricted keys are safe to include in client bundles — they cannot be used from other domains
  • The per-IP rate limit prevents individual users from exhausting your key's quota
  • For server-side use, create a separate key without allowed_origins
  • Never embed unrestricted keys in client-side code