Cube.js Server
Cube.js Server (`@cubejs-backend/server`) is the core Node.js component of the Cube.js analytics platform, an open-source semantic layer for building analytical applications. It functions as a backend microservice that manages connections to various data sources (SQL databases, data warehouses), handles query queuing, caching, and pre-aggregations, and exposes a GraphQL/REST API for frontend applications. The current stable version, as per recent npm releases, is around 1.6.x, while the user provided 0.33.8 which is an older minor version. Cube.js releases new versions frequently, sometimes introducing breaking changes even in minor updates within a major series (e.g., 0.x.x versions). Its key differentiators include a SQL-based data schema for defining measures and dimensions, advanced pre-aggregation for performance, robust caching, enterprise-grade security (JWT tokens, row-level security), and visualization-agnostic API support, allowing integration with any frontend framework or BI tool.
Common errors
-
Error: Cannot find module 'pg'
cause The required database driver for PostgreSQL is not installed. This applies to any database type (e.g., `mysql2` for MySQL).fixInstall the necessary database driver: `npm install pg` (for PostgreSQL) or `yarn add pg`. -
Error: Data source is not configured. Please check your CUBEJS_DB_* environment variables.
cause Cube.js cannot connect to the database because environment variables (like `CUBEJS_DB_TYPE`, `CUBEJS_DB_HOST`, `CUBEJS_DB_NAME`, etc.) are either missing or incorrect, or the `.env` file is not loaded.fixEnsure that your `.env` file exists and contains all necessary `CUBEJS_DB_*` variables for your database, and that `dotenv.config()` is called correctly at the start of your application. Verify database credentials and host accessibility. -
Error: 'CUBEJS_API_SECRET' is not set. It is required to secure your API. Please set it via environment variable or in Cube.js options.
cause The `CUBEJS_API_SECRET` environment variable or the `apiSecret` option in `CubejsServer` constructor is not provided. This secret is crucial for securing your Cube.js API.fixSet `CUBEJS_API_SECRET` in your `.env` file (e.g., `CUBEJS_API_SECRET=YOUR_SECURE_SECRET`) or pass it directly in the `CubejsServer` constructor options. Ensure it's a strong, unique secret for production. -
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'
cause This low-level error often indicates a corrupted Cube Store metastore, especially when using Cube Store as the caching/queue engine, typically due to improper shutdown.fixTry deleting the `.cubestore` directory in your project root to clear the corrupted metastore. Note that this will clear your cache and pre-aggregations, which will be rebuilt on restart.
Warnings
- breaking The package name for the Cube.js server was changed from `cubejs-server` (deprecated) to `@cubejs-backend/server`. Using the old package name will result in an outdated, unmaintained version and potential compatibility issues. Ensure all dependencies and imports reflect `@cubejs-backend/server`.
- gotcha Database drivers (e.g., `pg`, `mysql2`, `mongodb`, `clickhouse`) are peer dependencies of Cube.js. You must explicitly install the correct driver package for your specific database(s) alongside `@cubejs-backend/server`.
- breaking Cube.js `0.x.x` versions, while actively developed, may introduce breaking changes in minor releases. Always consult the release notes and changelog before upgrading, especially regarding schema definitions, configuration formats (e.g., from `cube.js` to `cube.config.js` or `.env` for database credentials), and API scopes.
- breaking Node.js version support has evolved. Node.js v12 and v15 support was dropped with v0.32.0, and v14 was deprecated shortly after. Newer versions prioritize Node.js v16 and above. Using unsupported Node.js versions can lead to unexpected errors or stability issues.
- deprecated Embedding Cube.js directly into existing Express applications using `initApp(app)` has been deprecated in favor of deploying Cube.js as a separate microservice. While still functional, this pattern is less performant and reliable for production deployments, especially as Cube.js evolves towards Rust-based components.
Install
-
npm install cubejs-server -
yarn add cubejs-server -
pnpm add cubejs-server
Imports
- CubejsServer
const CubejsServer = require('cubejs-server');import { CubejsServer } from '@cubejs-backend/server'; - CubejsServerOptions
import { CubejsServerOptions } from '@cubejs-backend/server'; - generate
import { CubejsServer } from '@cubejs-backend/server'; const { generate } = new CubejsServer();import { generate } from '@cubejs-backend/server';
Quickstart
import express from 'express';
import { CubejsServer } from '@cubejs-backend/server';
import dotenv from 'dotenv';
import path from 'path';
dotenv.config({ path: path.resolve(process.cwd(), '.env') });
async function main() {
const server = new CubejsServer({
// Required for security and API token generation
// Use process.env.CUBEJS_API_SECRET ?? '' for production
apiSecret: process.env.CUBEJS_API_SECRET ?? 'YOUR_API_SECRET',
// Configure your database connection
dbType: process.env.CUBEJS_DB_TYPE ?? 'postgres',
dbHost: process.env.CUBEJS_DB_HOST ?? 'localhost',
dbName: process.env.CUBEJS_DB_NAME ?? 'cubejs_data',
dbUser: process.env.CUBEJS_DB_USER ?? 'cubejs_user',
dbPass: process.env.CUBEJS_DB_PASS ?? 'cubejs_password',
// Path to your Cube.js schema files (e.g., .js, .yml)
// Defaults to 'schema' folder in the root
// schemaPath: path.resolve(process.cwd(), 'schema'),
// Port for the Cube.js API
port: parseInt(process.env.PORT ?? '4000', 10),
// Enable developer playground in development mode
devPlayground: process.env.NODE_ENV === 'development',
// Additional server configuration options
// full stack traces for development debugging
extendContext: (req) => ({
traceId: req.headers['x-request-id'] || 'no-trace',
}),
});
const app = express();
// Integrate Cube.js with your Express app
await server.initApp(app);
app.listen(server.options.port, () => {
console.log(`🚀 Cube.js server is running on http://localhost:${server.options.port}`);
if (server.options.devPlayground) {
console.log(`▶️ Cube.js Playground available at http://localhost:${server.options.port}`);
}
});
}
main().catch((e) => {
console.error('Failed to start Cube.js server:', e);
process.exit(1);
});