NODE.JS / TYPESCRIPT
Node.js
The API is four JSON endpoints, so the built-in fetch in Node.js 18+ is all you need. No package to install.
There is no maintained SDK for the current API. The npm package zerocarbon-nodejs-sdk (2.0.0) was published for an earlier version: its default host (api.zerocarbon.codes) does not resolve, its flight method cannot send distance_km, and its report and webhook methods call endpoints that do not exist. Don't use it; use the client below.
A small typed client
zerocarbon.tstypescript
const BASE = 'https://zerocarbon.org.in/api/v1';
export interface Calculation {
emissions_kg_co2e: number;
emission_factor: number;
emission_factor_label: string;
emission_factor_source: string;
scope: 'scope_1' | 'scope_2' | 'scope_3';
activity: { value: number; unit: string };
formula: string | null;
details: Record<string, unknown>;
}
export class ZeroCarbonError extends Error {
constructor(public status: number, public code: string, message: string) {
super(message);
}
}
type Endpoint = 'electricity' | 'fuel' | 'flight' | 'spend';
export async function calculate(endpoint: Endpoint, body: object, apiKey = process.env.ZEROCARBON_API_KEY): Promise<Calculation> {
const res = await fetch(`${BASE}/calculate/${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
},
body: JSON.stringify(body),
});
const json = await res.json();
if (json.success) return json.data;
// Refusals: { error: string, code, guidance }. Other errors: { error: { code, message } }.
if (typeof json.error === 'string') throw new ZeroCarbonError(res.status, json.code, `${json.error} ${json.guidance ?? ''}`);
throw new ZeroCarbonError(res.status, json.error?.code ?? 'HTTP_' + res.status, json.error?.message ?? res.statusText);
}Usage
example.tstypescript
import { calculate, ZeroCarbonError } from './zerocarbon';
const grid = await calculate('electricity', { kwh: 1000, country_code: 'IN' });
console.log(grid.emissions_kg_co2e, grid.emission_factor_source);
// 675 CEA_CO2_Baseline_v22_FY2025-26
try {
await calculate('flight', { passengers: 2 });
} catch (err) {
if (err instanceof ZeroCarbonError) console.log(err.status, err.code);
// 422 distance_required
}Run with npx tsx example.ts. Without ZEROCARBON_API_KEY set, electricity, fuel and flight run in test mode; spend needs the key. Fields for each endpoint are in the API Reference.