npm package: @gzl10/nexus-backend
Description: Backend as a Service (BaaS) with Express 5, Knex and CASL
Author: Gonzalo Díez
Latest version: 0.21.0

# @gzl10/nexus-backend

[![npm version](https://img.shields.io/npm/v/@gzl10/nexus-backend.svg)](https://www.npmjs.com/package/@gzl10/nexus-backend)
[![npm downloads](https://img.shields.io/npm/dm/@gzl10/nexus-backend.svg)](https://www.npmjs.com/package/@gzl10/nexus-backend)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

> **Warning**: This project is in experimental phase. Use at your own risk.

Backend as a Service (BaaS) with Express 5, Knex, and CASL. Build modular, type-safe backends with authentication, authorization, and real-time features.

**Repository**: [gitlab.gzl10.com/oss/nexus](https://gitlab.gzl10.com/oss/nexus)

## Installation

```bash
pnpm add @gzl10/nexus-backend
```

## Quick Start

```typescript
import { start } from '@gzl10/nexus-backend'

await start({
  port: 3000,
  database: { url: 'file:./data/nexus.db' }
})
```

## Features

### Core Modules

| Module | Description |
| ------ | ----------- |
| **auth** | JWT authentication with access/refresh tokens, OTP challenge, password reset |
| **users** | User management with multi-role support |
| **storage** | File storage (local/S3), thumbnails, deduplication |
| **mail** | Email sending via SMTP (Nodemailer) |
| **notifications** | In-app notification system |
| **schedules** | Scheduled tasks (cron jobs) |
| **compliance** | GDPR consent tracking, legal documents |
| **tags** | Tagging system for any entity |
| **links** | Entity relationships and linking |

### Platform Features

| Feature | Description |
| ------- | ----------- |
| **Express 5** | Modern async error handling |
| **Multi-DB** | SQLite, PostgreSQL, MySQL via Knex |
| **CASL** | Attribute-based access control with multi-role |
| **Socket.IO** | Real-time events and notifications |
| **Plugin Architecture** | Extend with custom modules and plugins |
| **OpenAPI** | Auto-generated API documentation |
| **Rate Limiting** | Built-in rate limiting middleware |

## Configuration

```typescript
import { start } from '@gzl10/nexus-backend'

await start({
  port: 3000,
  host: '0.0.0.0',

  // Frontend SPA
  ui: {
    enabled: true,
    base: '/',
    path: '../ui/dist'
  },

  // Custom routes
  beforeRoutes: (app) => {
    app.get('/api/health_custom', (_req, res) => res.json({ ok: true }))
  },
  afterRoutes: (app, serveSPA) => {
    serveSPA('/admin', '../admin/dist')
  },

  // Event subscriptions
  events: {
    'auth.login': ({ userId }) => console.log('Login:', userId),
    'db.users.created': ({ data }) => console.log('New user:', data.email)
  },

  // Custom CASL rules
  casl: (user, { can }) => {
    if (user.email.endsWith('@admin.com')) can('manage', 'all')
  },

  // Lifecycle hooks
  onReady: (app, port, host) => console.log(`Ready at ${host}:${port}`),
  beforeClose: () => console.log('Shutting down...')
})
```

### Config Options

| Option | Type | Default | Description |
| ------ | ---- | ------- | ----------- |
| `port` | `number` | `3000` | Server port |
| `host` | `string` | `0.0.0.0` | Server host |
| `ui.enabled` | `boolean` | `true` | Serve frontend SPA |
| `ui.base` | `string` | `/` | Base path for UI |
| `ui.path` | `string` | `../ui/dist` | Path to frontend dist |
| `database.url` | `string` | - | Database connection URL |
| `plugins` | `PluginManifest[]` | - | Plugins to register |
| `modules` | `ModuleManifest[]` | - | Standalone modules |
| `beforeRoutes` | `function` | - | Hook before module routes |
| `afterRoutes` | `function` | - | Hook after module routes |
| `events` | `object` | - | Event subscriptions |
| `casl` | `function` | - | Custom CASL rules |
| `onReady` | `function` | - | Server ready callback |
| `beforeClose` | `function` | - | Pre-shutdown callback |

### Environment Variables

```env
AUTH_SECRET=your-secret-key-min-32-chars  # Required (min 32 chars)
DATABASE_URL=file:./data/nexus.db         # SQLite, PostgreSQL, or MySQL
```

See `.env.example` for full list of options.

## Extending with Plugins

```typescript
import { start } from '@gzl10/nexus-backend'
import { cmsPlugin } from '@gzl10/nexus-plugin-cms'
import { myCustomModule } from './my-module'

await start({
  plugins: [cmsPlugin],
  modules: [myCustomModule]
})
```

## Exported Functions

| Function | Description |
| -------- | ----------- |
| `start(config?)` | Start the server |
| `stop()` | Stop the server |
| `restart(config?)` | Restart with new config |
| `db` | Knex database instance |
| `nexusEvents` | Event emitter for system events |
| `defineAbilityFor(user, permissions)` | Create CASL abilities |
| `getCoreModules()` | Get core modules list |
| `getUserModules()` | Get user modules list |

## CLI

```bash
# Database migrations
pnpm migrate dev            # Generate and apply migration (like Prisma)
pnpm migrate create <name>  # Generate migration from entities
pnpm migrate up             # Run pending migrations
pnpm migrate down           # Rollback last batch
pnpm migrate status         # Show migration status
pnpm migrate reset          # Reset database (dev only)

# Development
pnpm dev     # Start dev server
pnpm seed    # Seed database
```

## Stack

Express 5 | Knex | CASL | JWT | Socket.IO | Zod | Pino

## License

MIT