Installation
Quick Start
The Metrifox SDK supports a modern client-based architecture for better organization and type safety.
Configuration
Node.js:
import { init } from "metrifox-js";
const metrifoxClient = init({
apiKey: process.env.METRIFOX_API_KEY,
});
Vite/React:
import { init } from "metrifox-js";
const metrifoxClient = init({
apiKey: import.meta.env.VITE_METRIFOX_API_KEY,
});
window.metrifoxClient = metrifoxClient;
Alternative - Direct Initialization:
import { MetrifoxSDK } from "metrifox-js";
const sdk = new MetrifoxSDK({
apiKey: "your_api_key_here",
});
Get your API key from Settings → API Keys in your Metrifox dashboard.
Customer Management
Create a Customer
// Individual customer
const customer = await client.customers.create({
customer_key: "user_12345", // Required: unique identifier
customer_type: "INDIVIDUAL", // Required: "INDIVIDUAL" or "BUSINESS"
primary_email: "john.doe@example.com", // Required
first_name: "John",
last_name: "Doe",
primary_phone: "+1234567890",
currency: "USD"
});
// Business customer
const customer = await client.customers.create({
customer_key: "company_abc123",
customer_type: "BUSINESS",
primary_email: "contact@acmecorp.com",
legal_name: "ACME Corporation LLC",
display_name: "ACME Corp",
website_url: "https://acmecorp.com"
});
Update a Customer
const response = await client.customers.update("user_12345", {
primary_email: "newemail@example.com",
first_name: "Jane",
currency: "EUR"
});
The customer_key cannot be changed after creation.
Get Customer Data
// Get basic customer data
const customer = await client.customers.get("customer_123");
// Get detailed customer information
const customerDetails = await client.customers.getDetails("customer_123");
// List customers with pagination
const customerList = await client.customers.list({
page: 1,
per_page: 50,
search_term: "john@example.com", // Optional
customer_type: "INDIVIDUAL", // Optional
date_created: "2025-09-01" // Optional
});
// Check active subscription
const isActive = await client.customers.checkActiveSubscription("customer_123");
Delete a Customer
const response = await client.customers.delete("customer_123");
Bulk CSV Upload
// File input from your form
const csvFile = document.getElementById("csv-input").files[0];
const response = await client.customers.uploadCsv(csvFile);
console.log(`Processed ${response.data.total_customers} customers`);
console.log(`Successful: ${response.data.successful_upload_count}`);
Usage Tracking & Access Control
Check Feature Access
const access = await client.usages.checkAccess({
featureKey: "premium_feature",
customerKey: "customer_123",
});
if (access.can_access) {
console.log(`Access granted. Balance: ${access.balance}`);
} else {
console.log(`Quota exceeded. Used: ${access.used_quantity}/${access.quota}`);
}
Record Usage Events
// Simple usage (amount = 1)
await client.usages.recordUsage({
customerKey: "customer_123",
eventName: "api_call",
});
// Custom amount for bulk operations
await client.usages.recordUsage({
customerKey: "customer_123",
eventName: "bulk_upload",
amount: 50,
});
// Advanced usage with metadata
await client.usages.recordUsage({
customerKey: "customer_123",
eventName: "premium_feature_used",
amount: 1,
credit_used: 25, // Optional: credits consumed
event_id: "evt_abc123", // Optional: unique identifier
timestamp: Date.now(), // Optional: custom timestamp
metadata: { // Optional: additional context
feature_type: "advanced_analytics",
session_id: "sess_xyz789"
}
});
Complete Usage Example
async function useFeature(metrifoxClient, customerKey, featureKey, eventName) {
try {
// 1. Check if customer has access
const access = await metrifoxClient.usages.checkAccess({
featureKey,
customerKey,
});
if (access.can_access) {
// 2. Perform the actual feature logic
const result = performFeatureLogic();
// 3. Record usage after successful completion
await metrifoxClient.usages.recordUsage({
customerKey,
eventName,
amount: result.unitsUsed || 1,
event_id: result.transactionId,
metadata: {
execution_time_ms: result.duration
}
});
return { success: true, data: result };
} else {
return {
success: false,
error: "Quota exceeded",
balance: access.balance,
};
}
} catch (error) {
return { success: false, error: error.message };
}
}
Checkout & Billing
Embed Checkout Pages
// Embed checkout pages within your application
await client.checkout.embed({
productKey: "your_product_key",
container: "#checkout-container", // CSS selector or DOM element
});
Generate Checkout URL
// Basic checkout URL
const url = await client.checkout.url({
offeringKey: "premium_plan"
});
// With billing interval
const url = await client.checkout.url({
offeringKey: "premium_plan",
billingInterval: "monthly"
});
// With customer key for pre-filled checkout
const url = await client.checkout.url({
offeringKey: "premium_plan",
billingInterval: "monthly",
customerKey: "customer_123"
});
Framework Integration
React/Vite
Setup in main.jsx:
import { init } from "metrifox-js";
const metrifoxClient = init({
apiKey: import.meta.env.VITE_METRIFOX_API_KEY,
});
window.metrifoxClient = metrifoxClient;
Use in components:
function FeatureButton({ customerKey }) {
const handleClick = async () => {
const client = window.metrifoxClient;
const access = await client.usages.checkAccess({
featureKey: "premium_feature",
customerKey,
});
if (access.can_access) {
await client.usages.recordUsage({
customerKey,
eventName: "button_clicked",
});
}
};
return <button onClick={handleClick}>Use Feature</button>;
}
Next.js
Setup in _app.js:
import { init } from "metrifox-js";
const metrifoxClient = init({
apiKey: process.env.METRIFOX_API_KEY,
});
export { metrifoxClient };
Express
import { init } from "metrifox-js";
import express from "express";
const app = express();
const metrifoxClient = init({
apiKey: process.env.METRIFOX_API_KEY,
});
app.get("/api/premium/:customerId", async (req, res) => {
const access = await metrifoxClient.usages.checkAccess({
featureKey: "premium_api",
customerKey: req.params.customerId,
});
if (!access.can_access) {
return res.status(403).json({ error: "Access denied" });
}
await metrifoxClient.usages.recordUsage({
customerKey: req.params.customerId,
eventName: "premium_api_call",
});
res.json({ data: "premium content" });
});
API Reference
Client Architecture
const client = init(config);
// Available modules:
client.usages; // Usage tracking and access control
client.customers; // Customer management
client.checkout; // Embedded checkout
Functions
Initialization:
init(config?) - Initialize and return the SDK client
Usage Module (client.usages):
checkAccess(request) - Check feature access for a customer
recordUsage(request) - Record a usage event
Customers Module (client.customers):
create(request) - Add a customer
update(customerKey, request) - Update a customer
list(params?) - Get a paginated list of customers
get(customerKey) - Get a customer
delete(customerKey) - Delete a customer
getDetails(customerKey) - Get detailed customer information
uploadCsv(file) - Upload a CSV list of customers
checkActiveSubscription(customerKey) - Check for active subscription
Checkout Module (client.checkout):
embed(config) - Embed checkout pages in your application
url(config) - Generate a checkout URL
TypeScript Support
All TypeScript types are available for import:
import {
AccessCheckRequest,
UsageEventRequest,
AccessResponse,
CustomerCreateRequest,
CustomerUpdateRequest,
CustomerListRequest,
APIResponse,
} from "metrifox-js";
Error Handling
try {
const access = await client.usages.checkAccess({ featureKey, customerKey });
} catch (error) {
// Handle network errors, invalid API key, etc.
console.error("Metrifox API error:", error.message);
}
Configuration
Environment Variables
Node.js:
METRIFOX_API_KEY=your_api_key_here
Vite:
VITE_METRIFOX_API_KEY=your_api_key_here
Create React App:
REACT_APP_METRIFOX_API_KEY=your_api_key_here
Custom URLs
const client = init({
apiKey: "your_api_key",
baseUrl: "https://custom-api.metrifox.com/api/v1/"
});
Default URLs
- Production API:
https://api.metrifox.com/api/v1/
- Meter Service:
https://api-meter.metrifox.com/
- Web App:
https://app.metrifox.com
Support
The JavaScript SDK works seamlessly across all modern JavaScript environments including Node.js, React, Next.js, Vue, and more.