Security & API Keys

NexaDB offers two production-ready security models: Binary protocol uses username/password (like MongoDB/PostgreSQL), while HTTP REST API uses API keys.

🔒 Two Production-Ready Security Models

Choose the authentication model that fits your tech stack:

⚡ Binary Protocol (Username/Password):

  • PRODUCTION-READY - Just like MongoDB, PostgreSQL
  • • Default user: root / nexadb123
  • • 10x faster than HTTP REST (MessagePack encoding)
  • • Perfect for Node.js, Python, NestJS, Go, Rust
  • • Simple username/password authentication
  • • Secure: SHA-256 password hashing, per-connection sessions

🌐 HTTP REST API (API Keys):

  • PRODUCTION-READY - Standard REST API
  • • API keys with SHA-256 hashing
  • • RBAC with 4 roles (Admin, Write, Read, Guest)
  • • Rate limiting, audit logs, expiration
  • • Perfect for Java, PHP, Ruby, or any HTTP client

Default Credentials

⚡ Binary Protocol

Default username/password created on first startup:

Username: root
Password: nexadb123

⚠️ Change this password in production! See user management below.

🌐 HTTP REST API

Default admin API key printed on first startup:

Key: 32833cd0bc7b0f579ab5f045eb7409c8
Header: X-API-Key

Save this key! Use it to create additional API keys.

How It Works

⚡ Binary Protocol (Port 6970)

✓ PRODUCTION READY - Fast & Secure

Username/password authentication

  • 10x faster than HTTP REST (MessagePack)
  • Secure: SHA-256 password hashing
  • Session-based per-connection auth
  • • Used by Node.js, Python, NestJS, Go, Rust
  • • Just like MongoDB, PostgreSQL
  • • Perfect for production!

🌐 HTTP REST API (Port 6969)

✓ PRODUCTION READY - Enterprise

API key authentication

  • API keys with X-API-Key header
  • RBAC: Admin, Write, Read, Guest roles
  • Enterprise: Rate limiting, audit logs
  • • Used by Java, PHP, Ruby, or any HTTP client
  • • Key expiration & rotation
  • • Perfect for production!

Binary Protocol (Node.js/NestJS/Python)

Node.js with Binary Protocol

Install and use nexaclient (10x faster)
// Install the binary client
npm install nexaclient

const { NexaClient } = require('nexaclient');

// Connect with username/password (authentication in constructor)
const client = new NexaClient({
  host: 'localhost',
  port: 6970,
  username: 'root',
  password: 'nexadb123'
});
await client.connect();

// Query - secure and fast!
const results = await client.query('users', {
  age: { $gte: 18 }
});

// Create document
await client.create('users', {
  name: 'Alice',
  email: 'alice@example.com',
  age: 28
});

// Vector search
const similar = await client.vectorSearch('documents',
  [0.1, 0.2, 0.8],
  10,  // limit
  3    // dimensions
);

// Create new user (admin only)
await client.create_user('dev_user', 'password123', 'write');

NestJS with Binary Protocol

NestJS Service Example
// database.service.ts
import { Injectable } from '@nestjs/common';
import { NexaClient } from 'nexaclient';

@Injectable()
export class DatabaseService {
  private client: NexaClient;

  async onModuleInit() {
    // Connect with username/password from environment
    this.client = new NexaClient({
      host: 'localhost',
      port: 6970,
      username: process.env.NEXADB_USER || 'root',
      password: process.env.NEXADB_PASS || 'nexadb123'
    });
    await this.client.connect();
  }

  async findUsers(filter: any) {
    return this.client.query('users', filter);
  }

  async createUser(data: any) {
    return this.client.create('users', data);
  }
}

Python with Binary Protocol

Python Backend Example
# Install the binary client
pip install nexaclient

from nexaclient import NexaClient

# Connect with username/password (using context manager)
with NexaClient(host='localhost', port=6970, username='root', password='nexadb123') as client:
    # Query - secure and fast!
    users = client.query('users', {
        'age': {'$gte': 18}
    })

    # Create document
    client.create('users', {
        'name': 'Alice',
        'email': 'alice@example.com',
        'age': 28
    })

    # Vector search
    similar = client.vector_search('documents',
        [0.1, 0.2, 0.8],
        limit=10,
        dimensions=3
    )

    # Create new user (admin only)
    client.create_user('analyst', 'pass123', 'read')

HTTP REST API (Java/Go/Others)

Java with HTTP REST API

Java HTTP Client Example
// Java with OkHttp
OkHttpClient client = new OkHttpClient();

String apiKey = "32833cd0bc7b0f579ab5f045eb7409c8";

// Query users
String json = "{"filters":{"age":{"$gte":18}}}";
RequestBody body = RequestBody.create(json,
    MediaType.parse("application/json"));

Request request = new Request.Builder()
    .url("http://localhost:6969/collections/users/query")
    .addHeader("X-API-Key", apiKey)
    .post(body)
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

Go with HTTP REST API

Go HTTP Client Example
package main

import (
    "bytes"
    "net/http"
    "io/ioutil"
)

func main() {
    apiKey := "32833cd0bc7b0f579ab5f045eb7409c8"

    // Query users
    jsonData := []byte(`{"filters":{"age":{"$gte":18}}}`)

    req, _ := http.NewRequest("POST",
        "http://localhost:6969/collections/users/query",
        bytes.NewBuffer(jsonData))

    req.Header.Set("X-API-Key", apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    println(string(body))
}

Rust with HTTP REST API

Rust reqwest Example
use reqwest;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = "32833cd0bc7b0f579ab5f045eb7409c8";
    let client = reqwest::Client::new();

    // Query users
    let res = client
        .post("http://localhost:6969/collections/users/query")
        .header("X-API-Key", api_key)
        .json(&json!({
            "filters": {
                "age": {"$gte": 18}
            }
        }))
        .send()
        .await?;

    println!("{}", res.text().await?);
    Ok(())
}

Creating Additional API Keys

Admin Panel (Recommended)

The easiest way to create API keys is through the Admin Panel:

  1. Open http://localhost:9999
  2. Go to "Security" tab
  3. Click "Create API Key"
  4. Select role (Admin, Write, Read, Guest)
  5. Set expiration (days)
  6. Copy the generated key (shown only once!)

Via HTTP API

Create API Key Programmatically
# Use default admin key to create new keys
curl -X POST http://localhost:6969/api_keys \
  -H "X-API-Key: 32833cd0bc7b0f579ab5f045eb7409c8" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "backend_service",
    "role": "write",
    "expires_in_days": 90
  }'

# Response
{
  "api_key": "nxdb_abc123def456...",
  "username": "backend_service",
  "role": "write",
  "created_at": "2025-01-15T10:30:00Z",
  "expires_at": "2025-04-15T10:30:00Z"
}

# SAVE THIS KEY! It's only shown once!

RBAC Roles

Admin

Full access to everything

Create collections, manage users, create API keys, read/write/delete data, view audit logs
Write

Read and write data

Insert, update, delete documents. Query data. Cannot create collections or manage users.
Read

Read-only access

Query documents, vector search, view statistics. Cannot modify data.
Guest

Limited read access

Query public collections only. Rate limited to 10 req/min.

User Management with RBAC

Creating Users (Binary Protocol)
// Create users with different roles (admin only)
await client.create_user('alice', 'alice123', 'admin');  // Full access
await client.create_user('bob', 'bob123', 'write');      // Read/write data
await client.create_user('charlie', 'char123', 'read');  // Read-only
await client.create_user('guest', 'guest123', 'guest');  // Limited read

// List all users (admin only)
const users = await client.list_users();
console.log(users);

// Change password
await client.change_password('alice', 'newpass456');

// Delete user (admin only)
await client.delete_user('guest');

Password Management

🔑 Changing Your Password

You can change your password in two ways:

Method 1: Via Admin Panel (Recommended)

  1. Start the admin panel: nexadb admin
  2. Open http://localhost:9999/admin_panel/
  3. Log in with your current credentials
  4. Go to the "Users" tab
  5. Click "Change Password" for your user
  6. Enter your new password and confirm

Method 2: Via Binary Protocol Client

For programmatic password changes:

// JavaScript/Node.js
const client = new NexaClient({
  host: 'localhost',
  port: 6970,
  username: 'root',
  password: 'nexadb123'
});
await client.connect();
await client.change_password('root', 'new_secure_password');

# Python
with NexaClient(host='localhost', port=6970, username='root', password='nexadb123') as client:
    client.change_password('root', 'new_secure_password')

🔓 Forgot Your Password?

If you forget your root password, NexaDB provides a simple command-line tool to reset it without losing any data.

Reset to Default Password

$ nexadb reset-password

This resets the root password to nexadb123 without losing any collections, documents, or users.

Reset to Custom Password

$ nexadb reset-password --password my_new_password

Set a custom password during reset. All your data remains intact.

🔒 What Happens During Password Reset?

  • Data Safety: All collections, documents, and user data remain untouched
  • Users Preserved: All users and their roles stay intact
  • API Keys Unchanged: Existing API keys continue to work
  • Only Password Changed: Only the root user's password hash is updated

Security Best Practices

✓ Both Protocols Are Production-Ready

Binary (username/password) and HTTP (API keys) are both secure for production

Choose Based on Your Stack

Binary for Node.js/Python/NestJS (10x faster), HTTP for Java/PHP/Ruby

Change Default Password Immediately

Use the admin panel or nexadb reset-password --password your_password to set a secure password

Principle of Least Privilege

Analytics service = Read role, Backend API = Write role, Ops = Admin role

Store Credentials in Environment Variables

Never commit passwords or API keys to Git. Use .env files

Rotate Credentials Regularly

Change passwords and API keys every 90 days

✓ Production Ready

Both protocols are production-ready! Binary protocol uses username/password with RBAC (just like MongoDB/PostgreSQL), while HTTP REST API uses API keys with advanced features. Choose based on your tech stack, not security concerns!