npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nexabase/sdk

v2.11.0

Published

Official JavaScript/TypeScript SDK for NexaBase - Build apps faster with auto-generated APIs

Readme

@nexabase/sdk

Official JavaScript/TypeScript SDK for NexaBase - Build apps faster with auto-generated APIs

npm version npm downloads License: MIT TypeScript Node.js


📖 Quick Links


✨ 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/sdk

yarn

yarn add @nexabase/sdk

pnpm

pnpm add @nexabase/sdk

CDN (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

API Reference


🤝 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 build

See CONTRIBUTING.md for detailed guidelines.


📄 License

MIT License - see LICENSE file for details.


📞 Support