Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

dc-server-setup

/dc-server-setup

Konfiguruje stronę serwerową drizzle-cube: SemanticLayerCompiler, adaptery Express, Fastify, Hono i Next.js, extractSecurityContext dla wielu najemców, endpoint MCP, cache i RLS w Postgres.

Licencja
MIT
Ostatnia zmiana repozytorium
27.09.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
5
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 27.09.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Konfiguruje stronę serwerową drizzle-cube: SemanticLayerCompiler, adaptery Express, Fastify, Hono i Next.js, extractSecurityContext dla wielu najemców, endpoint MCP, cache i RLS w Postgres.

Wyzwalacze z opisu

add an analytics API
Oryginalny opis (EN)

Set up the drizzle-cube server side of an app — install, SemanticLayerCompiler, engineType, Express/Fastify/Hono/Next.js adapters, extractSecurityContext for multi-tenant auth, the built-in MCP endpoint for Claude/AI clients, caching, Postgres RLS, per-tenant cube sets. Use whenever someone wants to "add an analytics API" or serve cubes/MCP from an app using drizzle-cube (not for contributing to drizzle-cube).

Jak działa

  1. Install
  2. Minimal end-to-end: Hono + Postgres
  3. Rules
  4. I need to…
  5. Read next
Sekcje z nagłówków SKILL.md, w oryginale · 111 linii, 975 słów
Podgląd SKILL.md
---
name: dc-server-setup
description: Set up the drizzle-cube server side of an app — install, SemanticLayerCompiler, engineType, Express/Fastify/Hono/Next.js adapters, extractSecurityContext for multi-tenant auth, the built-in MCP endpoint for Claude/AI clients, caching, Postgres RLS, per-tenant cube sets. Use whenever someone wants to "add an analytics API" or serve cubes/MCP from an app using drizzle-cube (not for contributing to drizzle-cube).
---

# drizzle-cube server setup

This skill is for apps that use the `drizzle-cube` npm package (0.9.6 and later). It gets your cubes served over HTTP: Cube.js-compatible REST under `/cubejs-api/v1` and an MCP endpoint at `/mcp`.

Sibling skills cover the rest. Writing cubes (measures, dimensions, joins, the `sql` security filter) is in **dc-cubes**. Writing queries is in **dc-queries**. The React UI is in **dc-dashboards**; the client also needs `import 'drizzle-cube/client/styles.css'`.

## Install

```bash
npm install drizzle-cube drizzle-orm          # drizzle-orm ^0.45 is a peer dependency
npm install postgres                          # your driver: see references/engines.md
npm install hono @hono/node-server            # or: express cors | fastify | next
npm install jose                              # used below to verify JWTs; use your own auth lib if you have one
```

The Express adapter imports `cors` statically, so install `cors` even if you never pass the `cors` option. Fastify loads `@fastify/cors` only when you pass `cors`. It is not a peer dependency, so install it yourself if you use that option.

## Minimal end-to-end: Hono + Postgres

```ts
// src/server.ts
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { serve } from '@hono/node-server'
import { jwtVerify } from 'jose'
import { createCubeRoutes } from 'drizzle-cube/adapters/hono'
import type { SecurityContext } from 'drizzle-cube/server'
import { db } from './db'          // drizzle(postgres(url), { schema })
import { schema } from './schema'
import { ordersCube } from './cubes' // authored per the dc-cubes skill

const jwtSecret = process.env.JWT_SECRET
if (!jwtSecret) throw new Error('JWT_SECRET is required')
const secret = new TextEncoder().encode(jwtSecret)

type Env = { Variables: { securityContext: SecurityContext } }

// Authenticate BEFORE drizzle-cube runs: a throw inside extractSecurityContext
// surfaces as a 500, so reject bad tokens here with a real 401.
const requireTenant = createMiddleware<Env>(async (c, next) => {
  if (c.req.method === 'OPTIONS') return next() // let CORS preflights through
  const token = c.req.header('Authorization')?.replace(/^Bearer /, '')
  if (!token) return c.json({ error: 'Unauthorized' }, 401)
  try {
    const { payload } = await jwtVerify(token, secret)
    if (typeof payload.orgId !== 'number') return c.json({ error: 'No tenant' }, 403)
    c.set('securityContext', { organisationId: payload.orgId, userId: payload.sub })
  } catch {
    return c.json({ error: 'Invalid token' }, 401)
  }
  await next()
})

const app = new Hono<Env>()
app.use('/cubejs-api/*', requireTenant)
app.use('/mcp', requireTenant)

app.route('/', createCubeRoutes({
  cubes: [ordersCube],
  drizzle: db,
  schema,
  engineType: 'postgres',
  // Only ever read the context your middleware derived from the verified token.
  extractSecurityContext: (c) => c.get('securityContext')
}))

serve({ fetch: app.fetch, port: 3001 })
// REST: POST /cubejs-api/v1/load, GET /cubejs-api/v1/meta, ...   MCP: POST /mcp
```

Smoke test:

```bash
curl -H "Authorization: Bearer $TOKEN" localhost:3001/cubejs-api/v1/meta
curl -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"query":{"measures":["Orders.count"],"dimensions":["Orders.status"]}}' \
  localhost:3001/cubejs-api/v1/load
```

The object your extractor returns is the `securityContext`. Every cube's `sql` reads it as `ctx.securityContext.organisationId`, so its keys must match what your cubes expect.

## Rules

1. **Always pass `engineType`.** Without it, a driver that has `all` and `run` is treated as SQLite and every other driver with `execute` as Postgres. MySQL, SingleStore, DuckDB, Databend and Snowflake are never detected: they get Postgres SQL and fail at query time.
2. **Build the security context only from verified credentials**, such as a checked JWT, a server session or an API key looked up in your database. Never take it from a header, query param or body the client controls. It is the only tenant boundary, and cube `sql` filters trust it completely.
3. **Authenticate in middleware and keep `extractSecurityContext` trivial.** When the extractor throws, REST routes return 500, not 401. Rejecting in middleware gives clients correct status codes. Let `OPTIONS` through if you use CORS.
4. **Configure the compiler, not the adapter, once you own the compiler.** If you pass `semanticLayer`, the adapter ignores `cubes`, `cache`, `rlsSetup`, `engineType`, `drizzle` and `schema`. Put them on `new SemanticLayerCompiler({...})` instead. Cube sets and direct `execute()` calls need a compiler you own.
5. **Every compiler read takes a security context.** Since 0.8, `execute(query, ctx)`, `dryRun`, `getMetadata`, `validateQuery`, `getCube`, `getAllCubes`, `getCubeNames` and `hasCube` all require one, because cube shape can differ per tenant. Deployments with no tenancy pass `SINGLE_TENANT_CONTEXT`. The compiler has no `load()` method.
6. **MCP is on by default at `/mcp`, so lock it down.** It uses the same `extractSecurityContext` as REST. By default only loopback origins and clients that send no `Origin` header are allowed. Browser or hosted clients that send `Origin` need `mcp.allowedOrigins`. Public deployments should also set `mcp.resourceMetadataUrl` (OAuth). If you don't want MCP, pass `mcp: { enabled: false }`.
7. **Never cache `/cubejs-api/*` or `/mcp` in a shared cache or CDN.** Responses are tenant-scoped, including `/meta`. drizzle-cube sends `Cache-Control: private, no-store` for this reason. Use the built-in result cache instead (references/multi-tenancy.md).
8. **Create one compiler per process and register cubes at boot.** The compiler holds metadata caches and cube-set state in memory. Building it per request throws that away. With several processes, each one must register the same cubes and cube sets.

## I need to…

Open only the reference your task needs.

| Need | Read |
|---|---|
| Express, Fastify or Next.js instead of Hono, plus CORS, the endpoint list and adapter options | references/adapters.md |
| MySQL, SQLite, SingleStore, DuckDB, Databend, Snowflake or Neon. Which analysis modes each engine supports | references/engines.md |
| Connect Claude, Claude Code or another AI client. Custom MCP instructions, OAuth, the chart app. Cube tools inside my own MCP server | references/mcp.md |
| Design the security context. Postgres RLS. Different cubes per tenant (cube sets). Result caching, Redis, invalidation | references/multi-tenancy.md |
| Run queries from server code (jobs, tests) without HTTP | `semanticLayer.execute(query, ctx)`; see references/multi-tenancy.md, "Calling the compiler directly" |

## Read next

- **dc-cubes**: every cube's `sql` must filter by `ctx.securityContext`. This skill only supplies the context.
- **dc-queries**: query shape for `/load`, and the funnel, flow and retention modes.
- **dc-dashboards**: point the React client at `/cubejs-api/v1` and send the same bearer token.
Pliki w paczce (5)
  • SKILL.md 7 KB
  • references/adapters.md 12 KB
  • references/engines.md 6 KB
  • references/mcp.md 9 KB
  • references/multi-tenancy.md 14 KB

Wersje

W bazie nie ma innych skilli o nazwie dc-server-setup.

Migawka bazy z 13.11.2026 · wersja paczki a0bf3dede2dd (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100dc-cubes
    Pisze definicje kostek drizzle-cube ze schematu Drizzle: defineCube, miary, wymiary, złączenia, filtrowanie najemców przez securityContext oraz miary obliczane, statystyczne i okienkowe.
  • 100dc-queries
    Pisze i naprawia zapytania semantyczne w stylu Cube.js dla drizzle-cube: miary, wymiary, filtry, okresy, porównania, lejki, retencja, a także odpowiada na pytania narzędziami MCP drizzle_cube_*.
  • 90add-chart-type
    Dodaje nowy wbudowany typ wykresu do drizzle-cube wraz z komponentem, konfiguracją i wpisem w rejestrze.
  • 100better-auth-hono
    Integruje Better Auth z Hono, Drizzle i PostgreSQL: montuje obsługę, sesje po stronie klienta, schemat i trasy chronione.
  • 100supabase
    Konfiguruje Supabase dla SaaS w Next.js: Drizzle z poolerem, logowanie wyłącznie przez Google, RLS i optymalizacja kosztów.
  • 100add-backend
    Obsługuje warstwę danych: wybiera jeden z sześciu szablonów backendu, podłącza do niego frontend i tworzy zasób CRUD z tabelą Postgres, hookami zapytań i stroną DataTable.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.