OneBalance API implements Cross Origin Resource Sharing (CORS) to allow requests from browsers on different domains.

Overview

CORS support enables web applications to make AJAX requests to the OneBalance API from domains different from where the API is hosted. This is essential for implementing features like dashboards or control panels that utilize the API.

How CORS Works

When a browser makes a cross-origin request:

  1. For non-simple requests (like PUT, DELETE, or with custom headers), the browser first sends a “preflight” request using the OPTIONS method
  2. This preflight request includes the Origin header identifying the requesting domain
  3. The server responds with headers describing the allowed constraints
  4. If the actual request falls within these constraints, the browser proceeds with the actual request

CORS Headers

The OneBalance API responds with the following CORS headers:

HeaderDescription
Access-Control-Allow-OriginThe domain that sent the request (from the Origin header)
Access-Control-Allow-MethodsThe HTTP methods allowed for cross-origin requests (typically includes all available methods)
Access-Control-Expose-HeadersHeaders that will be accessible to requests from the origin domain
Access-Control-Max-AgeHow long (in seconds) the preflight response can be cached before another preflight is needed
Access-Control-Allow-CredentialsSet to true to allow sending authentication credentials (like Access tokens) with the request

Client Implementation

Most browsers handle CORS details automatically. Your JavaScript code can make requests to the OneBalance API endpoints as it would to any API, and the browser will manage the preflight requests and handle the CORS headers.

request.js
// Example of a cross-origin fetch request
fetch('https://be.onebalance.io/api/assets/list', {
  method: 'GET',
  headers: {
    'x-api-key': 'your-api-key',
    'Content-Type': 'application/json',
  },
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Server Implementation in Next.js

In a Next.js application using the App Router, you can set CORS headers for a specific Route Handler using the standard Web API methods:

route.ts
// app/api/[...path]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { API_BASE_URL, API_KEY } from '@/lib/constants';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  const pathString = path.join('/');
  const searchParams = request.nextUrl.searchParams;

  try {
    // Build the API URL with any query parameters
    const apiUrl = new URL(`/api/${pathString}`, API_BASE_URL);
    searchParams.forEach((value, key) => {
      apiUrl.searchParams.append(key, value);
    });

    const response = await fetch(apiUrl.toString(), {
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': API_KEY,
      },
    });

    const data = await response.json();
    return NextResponse.json(data);
  } catch (error) {
    return NextResponse.json({ message: 'Failed to fetch data', error }, { status: 400 });
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  const pathString = path.join('/');

  try {
    const body = await request.json();

    const response = await fetch(`${API_BASE_URL}/api/${pathString}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': API_KEY,
      },
      body: JSON.stringify(body),
    });

    const data = await response.json();
    return NextResponse.json(data);
  } catch (error) {
    return NextResponse.json({ message: 'Failed to fetch data', error }, { status: 400 });
  }
}