@nexabase/sdk
v2.11.0
Published
Official JavaScript/TypeScript SDK for NexaBase - Build apps faster with auto-generated APIs
Maintainers
Readme
@nexabase/sdk
Official JavaScript/TypeScript SDK for NexaBase - Build apps faster with auto-generated APIs
📖 Quick Links
- Full Documentation - Complete guides and API reference
- NexaBase Platform - Learn about NexaBase BaaS
- Examples - Runnable code examples
- API Reference - Complete API documentation
- GitHub Issues - Report bugs or request features
✨ What is NexaBase?
NexaBase is a powerful Backend as a Service (BaaS) platform that automatically generates REST APIs from your data schemas. Think of it as Supabase + Firebase with auto-generated endpoints.
The @nexabase/sdk is the official JavaScript/TypeScript client that makes it easy to interact with your NexaBase backend from any JavaScript environment.
Key Benefits
- 🚀 Zero Backend Code - Define your schema, get instant REST APIs
- 🔌 Type-Safe - Full TypeScript support with IntelliSense
- ⚡ Real-time Ready - WebSocket subscriptions out of the box
- 🔐 Secure by Default - JWT, API keys, OAuth support
- 📦 All-in-One - Auth, Storage, Functions, Webhooks included
📦 Installation
npm
npm install @nexabase/sdkyarn
yarn add @nexabase/sdkpnpm
pnpm add @nexabase/sdkCDN (for browsers)
<script src="https://cdn.jsdelivr.net/npm/@nexabase/sdk@latest/dist/index.min.js"></script>🚀 Quick Start
1️⃣ Initialize the Client
import { createApiClient } from '@nexabase/sdk';
const nexabase = createApiClient(
'https://your-tenant.nexabase.app',
'your-api-key' // Get from NexaBase dashboard
);2️⃣ Authenticate (Optional)
// Sign in with email/password (API Key required)
const { access_token, user } = await nexabase.signInApi(
'[email protected]',
'your-password'
);
console.log(`Welcome, ${user.name}!`);3️⃣ Start Using APIs
// List all collections
const collections = await nexabase.listCollections();
console.log('Collections:', collections);
// Query documents with filters
const users = await nexabase.listDocuments('users', {
filter: { status: 'active' },
sort: '-created_at',
page: 1,
per_page: 20,
});
// Create a document
const newUser = await nexabase.createDocument('users', {
name: 'John Doe',
email: '[email protected]',
role: 'user',
});
// Update a document
await nexabase.updateDocument('users', newUser.id, {
last_login: new Date().toISOString(),
});
// Delete a document
await nexabase.deleteDocument('users', userId);
// Create document with file upload (NEW v2.11.0)
const file = document.querySelector('input[type="file"]').files[0];
await nexabase.createDocumentWithFile('products', { name: 'New Item' }, file, 'image');🎯 Core Features
🔐 Authentication
Multiple authentication methods supported:
import {
createApiClient, // API Key auth
createTokenClient, // Bearer token auth
createAuthenticatedApiClient // Auto login
} from '@nexabase/sdk';
// API Key (server-to-server)
const client = createApiClient(
'https://api.nexabase.app',
'your-api-key'
);
// Bearer Token (user-authenticated)
const client = createTokenClient(
'https://api.nexabase.app',
'jwt-token-here'
);
// Auto login (API Key + user credentials)
const client = await createAuthenticatedApiClient(
'https://api.nexabase.app',
'api-key',
'[email protected]',
'password'
);
// Subdomain client
const client = createSubdomainClient(
'mytenant', // Your tenant subdomain
'api-key'
);
// Connects to: https://mytenant.nexabase.app📚 Collections & Documents
Full CRUD operations with advanced querying:
// Create collection
await nexabase.createCollection({
name: 'products',
schema: {
fields: {
name: { type: 'string', required: true, maxLength: 255 },
price: { type: 'number', required: true, min: 0 },
description: { type: 'text' },
in_stock: { type: 'boolean', default: true },
},
timestamps: true,
},
});
// List collections
const collections = await nexabase.listCollections();
// Get collection by name
const collection = await nexabase.getCollection('products');
// Update collection
await nexabase.updateCollection('products', {
description: 'Product catalog',
is_active: true,
});
// Delete collection
await nexabase.deleteCollection('products');Document Operations
// Create document
const product = await nexabase.createDocument('products', {
name: 'iPhone 15',
price: 999.99,
in_stock: true,
});
// Get document
const doc = await nexabase.getDocument('products', productId);
// Update document
await nexabase.updateDocument('products', productId, {
price: 899.99,
});
// Delete document
await nexabase.deleteDocument('products', productId);🔍 Fluent Query Builder
Advanced querying with chainable syntax:
import { NexaQuery } from '@nexabase/sdk';
// Basic query
const { data } = await nexabase
.from('products')
.select('id,name,price')
.where('price', '>', 50)
.where('in_stock', true)
.sort('-created_at')
.limit(10)
.get();
// Advanced filters
const { data } = await nexabase
.from('products')
.where('category', 'in', ['electronics', 'books'])
.where('price', 'between', [100, 500])
.where('name', 'like', '%iphone%')
.logical('OR')
.get();
// Aggregations
const { data } = await nexabase
.from('orders')
.groupBy('status')
.count('*', 'total')
.sum('amount', 'total_amount')
.avg('amount', 'avg_amount')
.get();
// Date grouping
const { data } = await nexabase
.from('orders')
.groupBy('year(created_at)', 'month(created_at)')
.count('*', 'total')
.get();
// Search
const { data } = await nexabase
.from('products')
.search('iphone')
.get();
// First result
const first = await nexabase
.from('users')
.where('email', '[email protected]')
.first();Query Methods
| Method | Description | Example |
|--------|-------------|---------|
| select() | Select fields | .select('id,name,email') |
| fields() | Alias for select | .fields('id,name') |
| where() | Add filter | .where('status', 'active') |
| where() | Operator filter | .where('price', '>', 100) |
| logical() | AND/OR logic | .logical('OR') |
| sort() | Sort results | .sort('-created_at') |
| limit() | Limit results | .limit(20) |
| page() | Pagination | .page(2) |
| include() | Include metadata | .include('schema') |
| groupBy() | Group by field | .groupBy('status') |
| count() | Count records | .count('*', 'total') |
| sum() | Sum values | .sum('amount', 'total') |
| avg() | Average | .avg('price', 'avg_price') |
| min() | Minimum value | .min('price') |
| max() | Maximum value | .max('price') |
| month() | Extract month | .month('created_at') |
| year() | Extract year | .year('created_at') |
| day() | Extract day | .day('created_at') |
| search() | Text search | .search('keyword') |
| get() | Execute query | .get() |
| first() | Get first result | .first() |
👥 User Management
Complete user CRUD operations:
import { NexaUsers } from '@nexabase/sdk';
// List users
const users = await nexabase.users.list({
page: 1,
limit: 20,
search: 'john', // Search by name/email
});
// Get user
const user = await nexabase.users.get(userId);
// Create user
const newUser = await nexabase.users.create({
email: '[email protected]',
password: 'SecurePassword123!',
first_name: 'New',
last_name: 'User',
role: 'user', // 'user' | 'admin' | 'superadmin'
status: 'active',
});
// Update user
await nexabase.users.update(userId, {
first_name: 'Updated',
role: 'admin',
is_active: true,
});
// Resend invite
await nexabase.users.resendInvite(userId);
// Delete user
await nexabase.users.delete(userId);☁️ Cloud Functions
Invoke serverless functions:
import { NexaFunctions } from '@nexabase/sdk';
// Invoke function (POST)
const result = await nexabase.functions.invoke('calculate-totals', {
cartId: 'cart_123',
});
// Invoke with options
const result = await nexabase.functions.invoke('send-email', {
to: '[email protected]',
subject: 'Welcome!',
body: 'Hello!',
}, {
method: 'POST',
timeout: 10000,
headers: {
'X-Custom-Header': 'value',
},
});
// Invoke with GET
const result = await nexabase.functions.invoke('get-stats', {}, {
method: 'GET',
});
// List functions
const functions = await nexabase.functions.list();📁 Storage
File upload and management:
import { NexaStorage } from '@nexabase/sdk';
// Upload a file
const file = await nexabase.storage.upload(
'avatars', // Bucket name
fileBlob, // File object/Blob
'user-avatar.png' // Optional path
);
// Download a file
const blob = await nexabase.storage.download(fileId);
// Get signed URL (temporary access)
const url = await nexabase.storage.getSignedUrl(fileId, {
expiresIn: 3600, // 1 hour
});
// List files in bucket
const files = await nexabase.storage.listFiles('avatars', {
prefix: 'users/',
});
// Delete a file
await nexabase.storage.delete(fileId);🪝 Webhooks
Create and manage webhooks:
import { NexaWebhooks } from '@nexabase/sdk';
// List webhooks
const webhooks = await nexabase.webhooks.list();
// Create webhook
const webhook = await nexabase.webhooks.create({
name: 'Order Created',
url: 'https://your-api.com/webhooks/orders',
events: ['document:created'],
is_active: true,
});
// Get webhook
const webhook = await nexabase.webhooks.get(webhookId);
// Update webhook
await nexabase.webhooks.update(webhookId, {
name: 'Updated Name',
is_active: false,
});
// Delete webhook
await nexabase.webhooks.delete(webhookId);🔄 Real-time Subscriptions
Listen to data changes in real-time:
import { NexaBaseRealtime } from '@nexabase/sdk';
const realtime = new NexaBaseRealtime({
baseURL: 'https://your-tenant.nexabase.app',
apiKey: 'your-api-key',
token: 'jwt-token', // Optional
reconnect: true,
maxReconnectAttempts: 5,
reconnectInterval: 5000,
heartbeatInterval: 30000,
});
// Connect
await realtime.connect();
// Subscribe to collection events
const subscriptionId = realtime.subscribe(
'products',
(message) => {
console.log('Product changed:', message);
},
{
events: ['*'], // ['insert', 'update', 'delete'] or ['*']
}
);
// Subscribe with filters
realtime.subscribe(
'orders',
(message) => {
console.log('New admin order:', message);
},
{
events: ['insert'],
filters: { role: 'admin' },
}
);
// Broadcast message
realtime.broadcast('products', 'product:updated', {
productId: '123',
action: 'restock',
});
// Unsubscribe
realtime.unsubscribe(subscriptionId);
// Disconnect
realtime.disconnect();🎯 TypeScript Support
The SDK is built with TypeScript and provides full type definitions:
import {
NexaBase,
NexaBaseConfig,
Document,
Collection,
StandardResponse,
DocumentQueryOptions,
User,
CreateUser,
} from '@nexabase/sdk';
// Fully typed configuration
const config: NexaBaseConfig = {
baseURL: 'https://api.nexabase.app',
apiKey: 'your-key',
timeout: 30000,
debug: false,
};
// Type-safe queries
const options: DocumentQueryOptions = {
filter: { status: 'active' },
sort: '-created_at',
page: 1,
per_page: 20,
fields: 'id,name,email',
};
// Typed response
const response: StandardResponse<Document[]> = await nexabase.listDocuments(
'users',
options
);
// Access typed data
response.data.forEach((doc: Document) => {
console.log(doc.id, doc.created_at);
});🏭 Factory Functions
Pre-configured clients for common scenarios:
import {
createApiClient,
createTokenClient,
createAuthenticatedApiClient,
createSubdomainClient,
createDevelopmentClient,
createTestClient,
} from '@nexabase/sdk';
// API Key client (recommended)
const client = createApiClient(
'https://api.nexabase.app',
'your-api-key'
);
// Bearer token client
const client = createTokenClient(
'https://api.nexabase.app',
'jwt-token'
);
// Auto-login client
const client = await createAuthenticatedApiClient(
'https://api.nexabase.app',
'api-key',
'[email protected]',
'password'
);
// Subdomain client
const client = createSubdomainClient(
'mytenant',
'api-key',
'nexabase.app'
);
// Development client
const client = createDevelopmentClient(
'http://localhost:3000',
'dev-key',
{
debug: true,
timeout: 30000,
}
);
// Test client
const client = createTestClient(
'http://localhost:3000',
'test-key',
{
debug: true,
mockMode: true,
}
);🚨 Error Handling
Comprehensive error handling:
try {
const doc = await nexabase.getDocument('users', 'invalid-id');
} catch (error) {
if (error.statusCode === 404) {
console.error('Document not found');
} else if (error.statusCode === 401) {
console.error('Unauthorized - check your API key');
} else if (error.statusCode === 429) {
console.error('Rate limit exceeded');
} else {
console.error('Error:', error.message, error.details);
}
}⚙️ Configuration Options
Client Configuration
const client = new NexaBase({
// Required
baseURL: 'https://your-tenant.nexabase.app',
apiKey: 'your-api-key',
// Optional
token: 'jwt-token', // Bearer token
timeout: 30000, // Request timeout (ms)
debug: false, // Enable debug logging
customHeaders: { // Custom headers
'X-Custom-Header': 'value',
},
});Realtime Configuration
const realtime = new NexaBaseRealtime({
baseURL: 'https://your-tenant.nexabase.app',
apiKey: 'your-api-key',
token: 'jwt-token',
reconnect: true,
maxReconnectAttempts: 5,
reconnectInterval: 5000,
heartbeatInterval: 30000,
});🌍 Browser Support
| Browser | Version | Support | |---------|---------|---------| | Chrome | Last 2 versions | ✅ | | Firefox | Last 2 versions | ✅ | | Safari | Last 2 versions | ✅ | | Edge | Last 2 versions | ✅ | | Node.js | >= 18.0.0 | ✅ |
📚 Complete Documentation
This README provides a quick overview. For complete documentation:
Guides
- Getting Started - Complete setup guide
- Authentication - All auth methods
- Collections & Documents - Working with data
- Query Builder - Fluent queries
- Cloud Functions - Serverless functions
- Storage - File management
- Webhooks - Webhook setup
- User Management - User CRUD
- Real-time - WebSocket subscriptions
- Error Handling - Best practices
API Reference
- Complete API Reference - All methods documented
- TypeScript Types - Type definitions
🤝 Contributing
We welcome contributions! Here's how you can help:
Ways to Contribute
- 🐛 Report bugs
- 💡 Suggest features
- 📝 Improve documentation
- 🔧 Submit pull requests
- 💬 Help others in discussions
Development Setup
# Fork and clone
git clone https://github.com/fmirpe/nexabase-sdk.git
cd nexabase-sdk/javascript
# Install dependencies
npm install
# Start development
npm run dev
# Run tests
npm test
# Build
npm run buildSee CONTRIBUTING.md for detailed guidelines.
📄 License
MIT License - see LICENSE file for details.
📞 Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📖 Docs: Full Documentation
- 🌐 Website: NexaBase Platform
