@rebasepro/cli 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +0 -1
  2. package/dist/commands/api-keys.d.ts +1 -0
  3. package/dist/commands/generate_sdk.d.ts +1 -1
  4. package/dist/index.es.js +464 -58
  5. package/dist/index.es.js.map +1 -1
  6. package/dist/utils/project.d.ts +15 -0
  7. package/package.json +8 -9
  8. package/templates/template/backend/Dockerfile +4 -3
  9. package/templates/template/backend/functions/hello.ts +32 -32
  10. package/templates/template/backend/package.json +1 -1
  11. package/templates/template/backend/src/index.ts +1 -2
  12. package/templates/template/config/collections/posts.ts +4 -4
  13. package/templates/template/config/collections/presets/ecommerce/categories.ts +3 -1
  14. package/templates/template/config/collections/presets/ecommerce/orders.ts +3 -1
  15. package/templates/template/config/collections/presets/ecommerce/products.ts +3 -1
  16. package/templates/template/config/collections/tags.ts +1 -3
  17. package/templates/template/config/collections/users.ts +4 -5
  18. package/templates/template/frontend/Dockerfile +5 -3
  19. package/templates/template/package.json +3 -2
  20. package/templates/template/pnpm-workspace.yaml +2 -0
  21. package/templates/template/scripts/example.ts +5 -2
  22. package/skills/rebase-admin/SKILL.md +0 -710
  23. package/skills/rebase-api/SKILL.md +0 -662
  24. package/skills/rebase-api/references/.gitkeep +0 -3
  25. package/skills/rebase-auth/SKILL.md +0 -1143
  26. package/skills/rebase-auth/references/.gitkeep +0 -3
  27. package/skills/rebase-backend-postgres/SKILL.md +0 -633
  28. package/skills/rebase-backend-postgres/references/.gitkeep +0 -3
  29. package/skills/rebase-basics/SKILL.md +0 -749
  30. package/skills/rebase-basics/references/.gitkeep +0 -3
  31. package/skills/rebase-collections/SKILL.md +0 -1328
  32. package/skills/rebase-collections/references/.gitkeep +0 -3
  33. package/skills/rebase-cron-jobs/SKILL.md +0 -699
  34. package/skills/rebase-cron-jobs/references/.gitkeep +0 -1
  35. package/skills/rebase-custom-functions/SKILL.md +0 -233
  36. package/skills/rebase-deployment/SKILL.md +0 -885
  37. package/skills/rebase-deployment/references/.gitkeep +0 -3
  38. package/skills/rebase-design-language/SKILL.md +0 -692
  39. package/skills/rebase-email/SKILL.md +0 -701
  40. package/skills/rebase-email/references/.gitkeep +0 -1
  41. package/skills/rebase-entity-history/SKILL.md +0 -485
  42. package/skills/rebase-entity-history/references/.gitkeep +0 -1
  43. package/skills/rebase-local-env-setup/SKILL.md +0 -189
  44. package/skills/rebase-local-env-setup/references/.gitkeep +0 -3
  45. package/skills/rebase-realtime/SKILL.md +0 -755
  46. package/skills/rebase-realtime/references/.gitkeep +0 -3
  47. package/skills/rebase-sdk/SKILL.md +0 -594
  48. package/skills/rebase-sdk/references/.gitkeep +0 -0
  49. package/skills/rebase-storage/SKILL.md +0 -765
  50. package/skills/rebase-storage/references/.gitkeep +0 -3
  51. package/skills/rebase-studio/SKILL.md +0 -746
  52. package/skills/rebase-studio/references/.gitkeep +0 -3
  53. package/skills/rebase-ui-components/SKILL.md +0 -1488
  54. package/skills/rebase-ui-components/references/.gitkeep +0 -3
  55. package/skills/rebase-webhooks/SKILL.md +0 -623
  56. package/skills/rebase-webhooks/references/.gitkeep +0 -1
  57. package/templates/template/backend/drizzle.config.ts +0 -51
@@ -1,885 +0,0 @@
1
- ---
2
- name: rebase-deployment
3
- description: Guide for deploying Rebase applications. Use this skill when the user needs to deploy to Rebase Cloud, set up Docker, self-host on AWS/GCP/Hetzner, or use a PaaS like Railway or Render.
4
- ---
5
-
6
- # Rebase Deployment
7
-
8
- Rebase supports multiple deployment strategies — from fully managed Rebase Cloud to self-hosted Docker deployments.
9
-
10
- ## Deployment Options
11
-
12
- | Option | Best For | Complexity |
13
- |--------|----------|------------|
14
- | **Rebase Cloud** | Fastest setup, managed infrastructure | ⭐ Easy |
15
- | **Docker (Self-Hosted)** | Full control on any VPS or bare metal | ⭐⭐ Medium |
16
- | **AWS** | ECS/Fargate or EC2 with RDS PostgreSQL | ⭐⭐⭐ Advanced |
17
- | **GCP** | Cloud Run with Cloud SQL PostgreSQL | ⭐⭐⭐ Advanced |
18
- | **Azure** | Container Apps with Azure Database for PostgreSQL | ⭐⭐⭐ Advanced |
19
- | **Scaleway** | Serverless Containers with Managed PostgreSQL (EU-only) | ⭐⭐⭐ Advanced |
20
- | **Hetzner** | Cost-effective VPS with Docker Compose | ⭐⭐ Medium |
21
- | **PaaS** | Railway, Render, Fly.io — Docker-based platforms | ⭐⭐ Medium |
22
-
23
- ## Rebase Cloud
24
-
25
- The simplest deployment path. Sign up at [app.rebase.pro](https://app.rebase.pro).
26
-
27
- ```bash
28
- # 1. Authenticate
29
- rebase login
30
-
31
- # 2. Initialize (if new project)
32
- rebase init
33
-
34
- # 3. Deploy
35
- rebase deploy
36
-
37
- # Deploy to dev environment
38
- rebase deploy --env dev
39
- ```
40
-
41
- ---
42
-
43
- ## Docker (Self-Hosted)
44
-
45
- ### Production Dockerfile (Multi-Stage)
46
-
47
- The production Dockerfile is a **multi-stage build**. The build context is the **monorepo root** (where `pnpm-workspace.yaml` lives), not the app directory.
48
-
49
- > **IMPORTANT FOR AGENTS:** The Dockerfile uses `node:22-alpine`, `corepack enable` (NOT `npm install -g pnpm`), and requires the monorepo root as the build context. Never generate a single-stage Dockerfile or use `node:20`.
50
-
51
- ```dockerfile
52
- # ── Stage 1: Install + Build ─────────────────────────────────────────
53
- FROM node:22-alpine AS builder
54
-
55
- ENV PNPM_HOME="/pnpm"
56
- ENV PATH="$PNPM_HOME:$PATH"
57
- ENV CI=true
58
- RUN corepack enable
59
-
60
- RUN apk add --no-cache python3 make g++
61
-
62
- WORKDIR /app
63
-
64
- # Copy workspace root
65
- COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
66
-
67
- # Copy source packages and app
68
- COPY packages ./packages
69
- COPY app ./app
70
-
71
- # Install all dependencies with flat node_modules for Docker compatibility
72
- # (many packages rely on hoisted devDependencies like @vitejs/plugin-react)
73
- RUN pnpm install --shamefully-hoist
74
-
75
- # Build all packages using pnpm recursive with --no-bail.
76
- # Some packages may fail tsc declarations — that's fine, we only need vite bundles + esbuild outputs.
77
- RUN pnpm --filter './packages/*' -r --no-bail run build; exit 0
78
-
79
- # Build the backend (TypeScript → JavaScript), then resolve ESM import extensions
80
- # 1. tsc compiles TS→JS 2. tsc-alias resolves path aliases 3. sed adds .js to remaining relative imports
81
- RUN cd app/backend && npx tsc -p tsconfig.docker.json && npx tsc-alias -p tsconfig.docker.json -f \
82
- && find dist -name '*.js' -exec sed -i 's/from "\(\.[^"]*\)"/from "\1.js"/g; s/\.js\.js/.js/g' {} +
83
-
84
- # Build frontend (reads .env.production for VITE_API_URL etc.)
85
- RUN cd app/frontend && npx vite build
86
-
87
- # Prune devDependencies to reduce image size
88
- RUN pnpm install --shamefully-hoist --prod
89
-
90
- # ── Stage 2: Production Runtime ──────────────────────────────────────
91
- FROM node:22-alpine AS runtime
92
-
93
- ENV PNPM_HOME="/pnpm"
94
- ENV PATH="$PNPM_HOME:$PATH"
95
- ENV NODE_ENV=production
96
-
97
- RUN corepack enable
98
-
99
- # Security: run as non-root
100
- RUN addgroup -g 1001 rebase && adduser -u 1001 -G rebase -s /bin/sh -D rebase
101
-
102
- WORKDIR /app
103
-
104
- # Copy only production artifacts (node_modules already pruned of devDependencies)
105
- COPY --from=builder /app/package.json /app/pnpm-lock.yaml /app/pnpm-workspace.yaml ./
106
- COPY --from=builder /app/node_modules ./node_modules
107
- COPY --from=builder /app/packages ./packages
108
- COPY --from=builder /app/app ./app
109
-
110
- # Uploads directory with correct ownership
111
- RUN mkdir -p /app/app/uploads && chown -R rebase:rebase /app
112
-
113
- ENV STORAGE_PATH=/app/app/uploads
114
-
115
- USER rebase
116
-
117
- WORKDIR /app/app/backend
118
- EXPOSE 3001
119
-
120
- HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
121
- CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
122
-
123
- # Copy the entrypoint script and drizzle config for auto-migration
124
- COPY --from=builder /app/app/backend/entrypoint.sh ./entrypoint.sh
125
- COPY --from=builder /app/app/backend/drizzle.config.ts ./drizzle.config.ts
126
- COPY --from=builder /app/app/backend/drizzle ./drizzle
127
-
128
- # Auto-migrate then start the compiled JavaScript backend
129
- CMD ["sh", "entrypoint.sh"]
130
- ```
131
-
132
- **Build command** (run from monorepo root):
133
-
134
- ```bash
135
- docker build -t rebase-backend -f app/backend/Dockerfile .
136
- ```
137
-
138
- ### Docker Entrypoint (Auto-Migration)
139
-
140
- The Docker image uses an entrypoint script (`entrypoint.sh`) that **automatically runs database migrations** before starting the server. Migrations are non-fatal — if they fail (e.g. already applied), the server still starts.
141
-
142
- ```bash
143
- #!/bin/sh
144
- set -e
145
-
146
- echo "🔄 Running database migrations..."
147
- npx drizzle-kit migrate --config=drizzle.config.ts 2>&1 || echo "⚠️ Migrations skipped or failed (non-fatal)"
148
-
149
- echo "🚀 Starting Rebase backend..."
150
- exec node dist/app/backend/src/index.js
151
- ```
152
-
153
- > **IMPORTANT FOR AGENTS:** The entrypoint runs `drizzle-kit migrate` automatically on container start. Never add manual migration steps to a Dockerfile CMD — they are handled by `entrypoint.sh`.
154
-
155
- ### Docker Compose (Monorepo)
156
-
157
- This is the monorepo-internal Docker Compose (`app/backend/docker-compose.yml`). Note: the build context is `../..` (monorepo root).
158
-
159
- ```yaml
160
- services:
161
- db:
162
- image: postgres:18-alpine
163
- restart: unless-stopped
164
- environment:
165
- POSTGRES_USER: rebase
166
- POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-rebasepassword}
167
- POSTGRES_DB: rebase
168
- ports:
169
- - "5432:5432"
170
- volumes:
171
- - postgres_data:/var/lib/postgresql/data
172
- healthcheck:
173
- test: ["CMD-SHELL", "pg_isready -U rebase -d rebase"]
174
- interval: 5s
175
- timeout: 5s
176
- retries: 10
177
- start_period: 10s
178
- command:
179
- - "postgres"
180
- - "-c"
181
- - "shared_buffers=256MB"
182
- - "-c"
183
- - "max_connections=100"
184
- - "-c"
185
- - "log_min_duration_statement=1000"
186
-
187
- backend:
188
- build:
189
- context: ../..
190
- dockerfile: app/backend/Dockerfile
191
- restart: unless-stopped
192
- ports:
193
- - "${PORT:-3001}:3001"
194
- environment:
195
- DATABASE_URL: postgresql://rebase:${POSTGRES_PASSWORD:-rebasepassword}@db:5432/rebase
196
- ADMIN_CONNECTION_STRING: postgresql://rebase:${POSTGRES_PASSWORD:-rebasepassword}@db:5432/rebase
197
- JWT_SECRET: ${JWT_SECRET:-super-secret-jwt-key-change-in-production}
198
- NODE_ENV: ${NODE_ENV:-development}
199
- PORT: "3001"
200
- ALLOW_REGISTRATION: ${ALLOW_REGISTRATION:-true}
201
- depends_on:
202
- db:
203
- condition: service_healthy
204
- volumes:
205
- - uploads:/app/app/backend/uploads
206
-
207
- volumes:
208
- postgres_data:
209
- driver: local
210
- uploads:
211
- driver: local
212
- ```
213
-
214
- > **WARNING FOR AGENTS:** The build context is `../..` (monorepo root), NOT `.` or `app/backend`. The Dockerfile path is relative to the monorepo root: `app/backend/Dockerfile`. The `depends_on` uses `condition: service_healthy` so the backend waits for postgres to be ready. **Never use `version: '3.8'`** — modern Docker Compose doesn't use the `version` key.
215
-
216
- ### Docker Compose (User Template)
217
-
218
- For user-generated projects (created via `rebase init`), the Docker Compose file is at the project root. It includes separate backend + frontend services:
219
-
220
- ```yaml
221
- services:
222
- db:
223
- image: postgres:18-alpine
224
- restart: unless-stopped
225
- environment:
226
- POSTGRES_USER: rebase
227
- POSTGRES_PASSWORD: ${DATABASE_PASSWORD:-changeme}
228
- POSTGRES_DB: rebase
229
- ports:
230
- - "5432:5432"
231
- volumes:
232
- - postgres_data:/var/lib/postgresql/data
233
- healthcheck:
234
- test: ["CMD-SHELL", "pg_isready -U rebase -d rebase"]
235
- interval: 5s
236
- timeout: 5s
237
- retries: 10
238
- start_period: 10s
239
- command:
240
- - "postgres"
241
- - "-c"
242
- - "shared_buffers=256MB"
243
- - "-c"
244
- - "max_connections=100"
245
- - "-c"
246
- - "work_mem=4MB"
247
- - "-c"
248
- - "effective_cache_size=768MB"
249
- - "-c"
250
- - "log_min_duration_statement=1000"
251
-
252
- backend:
253
- build:
254
- context: .
255
- dockerfile: backend/Dockerfile
256
- restart: unless-stopped
257
- ports:
258
- - "${PORT:-3001}:3001"
259
- env_file: .env
260
- environment:
261
- DATABASE_URL: postgresql://rebase:${DATABASE_PASSWORD:-changeme}@db:5432/rebase?options=-c%20search_path=public
262
- ADMIN_CONNECTION_STRING: postgresql://rebase:${DATABASE_PASSWORD:-changeme}@db:5432/rebase?options=-c%20search_path=public
263
- NODE_ENV: production
264
- PORT: "3001"
265
- depends_on:
266
- db:
267
- condition: service_healthy
268
- volumes:
269
- - uploads:/app/backend/uploads
270
-
271
- frontend:
272
- build:
273
- context: .
274
- dockerfile: frontend/Dockerfile
275
- restart: unless-stopped
276
- ports:
277
- - "80:80"
278
- depends_on:
279
- - backend
280
-
281
- volumes:
282
- postgres_data:
283
- driver: local
284
- uploads:
285
- driver: local
286
- ```
287
-
288
- Key differences from the monorepo compose:
289
- - Build context is `.` (project root), dockerfile is `backend/Dockerfile`
290
- - Uses `env_file: .env` to load all env vars
291
- - Sets `NODE_ENV: production` explicitly
292
- - Includes a separate `frontend` service (nginx)
293
- - Adds Postgres tuning for `work_mem` and `effective_cache_size`
294
-
295
- ---
296
-
297
- ## Environment Variables
298
-
299
- ### `loadEnv()` — Validated Environment Loading
300
-
301
- All environment variables are validated at startup via a Zod schema in `loadEnv()` from `@rebasepro/server-core`. The server **fails immediately** if required variables are missing or invalid.
302
-
303
- ```typescript
304
- import dotenv from "dotenv";
305
- import { loadEnv } from "@rebasepro/server-core";
306
-
307
- dotenv.config({ path: "../../.env" });
308
-
309
- // Basic — just Rebase env vars:
310
- export const env = loadEnv();
311
- ```
312
-
313
- > **IMPORTANT FOR AGENTS:** `loadEnv()` does NOT load `.env` files itself. You MUST call `dotenv.config()` (or use `--env-file`, container injection, etc.) **before** calling `loadEnv()`. This is a deployment concern, not a framework concern.
314
-
315
- ### Extending with Custom Variables
316
-
317
- Use the `extend` option to add your own typed env variables on top of the base Rebase schema:
318
-
319
- ```typescript
320
- import dotenv from "dotenv";
321
- import { loadEnv, z } from "@rebasepro/server-core";
322
-
323
- dotenv.config({ path: "../../.env" });
324
-
325
- export const env = loadEnv({
326
- extend: z.object({
327
- SMTP_HOST: z.string().optional(),
328
- SMTP_PORT: z.string().default("587").transform(Number),
329
- STRIPE_SECRET_KEY: z.string(),
330
- })
331
- });
332
- // env.SMTP_HOST → string | undefined (fully typed)
333
- // env.STRIPE_SECRET_KEY → string (validated, required)
334
- ```
335
-
336
- The `extend` schema is merged with the base `rebaseEnvSchema` using Zod's `.merge()`. All base variables remain available alongside your custom ones.
337
-
338
- ### `loadEnv()` Function Signature
339
-
340
- ```typescript
341
- function loadEnv(): RebaseEnv;
342
- function loadEnv<E extends z.AnyZodObject>(options: { extend: E }): RebaseEnv & z.infer<E>;
343
- ```
344
-
345
- ### Complete Environment Variable Reference
346
-
347
- All variables recognized by the base `rebaseEnvSchema`:
348
-
349
- | Variable | Type | Required | Default | Description |
350
- |----------|------|----------|---------|-------------|
351
- | `DATABASE_URL` | `string` (URL) | ✅ Yes | — | PostgreSQL connection string |
352
- | `ADMIN_CONNECTION_STRING` | `string` (URL) | No | — | Separate admin connection for migrations |
353
- | `JWT_SECRET` | `string` (≥32 chars) | ✅ Yes | Auto-generated (dev only) | JWT signing secret |
354
- | `JWT_ACCESS_EXPIRES_IN` | `string` | No | `"1h"` | JWT access token expiry (e.g. `"1h"`, `"30m"`) |
355
- | `JWT_REFRESH_EXPIRES_IN` | `string` | No | `"30d"` | JWT refresh token expiry |
356
- | `NODE_ENV` | `enum` | No | `"development"` | `"development"`, `"production"`, or `"test"` |
357
- | `PORT` | `string` → `number` | No | `"3001"` → `3001` | Server port (string, transformed to number) |
358
- | `CORS_ORIGINS` | `string` | ⚠️ Prod | — | Comma-separated allowed origins |
359
- | `FRONTEND_URL` | `string` | ⚠️ Prod | — | Frontend URL (CORS fallback, email links) |
360
- | `ALLOW_REGISTRATION` | `boolString` | No | `"false"` → `false` | Enable new user self-registration |
361
- | `ALLOW_LOCALHOST_IN_PRODUCTION` | `optionalBoolString` | No | `undefined` → `false` | Allow localhost URLs in production |
362
- | `GOOGLE_CLIENT_ID` | `string` | No | — | Google OAuth client ID |
363
- | `GOOGLE_CLIENT_SECRET` | `string` | No | — | Google OAuth client secret |
364
- | `REBASE_SERVICE_KEY` | `string` | No | Auto-generated (dev only) | Service-to-service auth key (≥32 chars) |
365
- | `DB_POOL_MAX` | `string` → `number` | No | `"20"` → `20` | Max database pool connections |
366
- | `DB_POOL_IDLE_TIMEOUT` | `string` → `number` | No | `"30000"` → `30000` | Idle connection timeout (ms) |
367
- | `DB_POOL_CONNECT_TIMEOUT` | `string` → `number` | No | `"10000"` → `10000` | Connection timeout (ms) |
368
- | `DATABASE_DIRECT_URL` | `string` (URL) | No | — | Direct database URL (bypasses pooler) |
369
- | `DATABASE_READ_URL` | `string` (URL) | No | — | Read replica database URL |
370
- | `STORAGE_TYPE` | `enum` | No | `"local"` | `"local"` or `"s3"` |
371
- | `STORAGE_PATH` | `string` | No | — | Local file storage directory |
372
- | `FORCE_LOCAL_STORAGE` | `optionalBoolString` | No | `undefined` → `false` | Suppress local-storage-in-production warning |
373
- | `S3_BUCKET` | `string` | If S3 | — | S3 bucket name |
374
- | `S3_REGION` | `string` | No | — | S3 region |
375
- | `S3_ACCESS_KEY_ID` | `string` | If S3 | — | S3 access key |
376
- | `S3_SECRET_ACCESS_KEY` | `string` | If S3 | — | S3 secret key |
377
- | `S3_ENDPOINT` | `string` (URL) | No | — | Custom S3 endpoint (MinIO, R2) |
378
- | `S3_FORCE_PATH_STYLE` | `optionalBoolString` | No | `undefined` → `false` | Use path-style S3 URLs (required for MinIO) |
379
-
380
- ### Zod Type Helpers
381
-
382
- | Helper | Accepts | Result |
383
- |--------|---------|--------|
384
- | `boolString` | `"true"`, `"false"`, `""` | Defaults to `"false"`, transforms to `boolean` |
385
- | `optionalBoolString` | `"true"`, `"false"`, `""`, `undefined` | Transforms `"true"` → `true`, everything else → `false` |
386
-
387
- ### Auto-Generated Secrets (Dev Only)
388
-
389
- In non-production mode, `loadEnv()` auto-generates ephemeral secrets for:
390
- - `JWT_SECRET` — if not set
391
- - `REBASE_SERVICE_KEY` — if not set
392
-
393
- These are random hex strings generated via `crypto.randomBytes(48)`. A warning is logged:
394
-
395
- ```
396
- ⚠️ Auto-generated secrets for: JWT_SECRET, REBASE_SERVICE_KEY. These are ephemeral — existing tokens will be invalidated on restart. Set them explicitly in .env for persistent sessions.
397
- ```
398
-
399
- > **WARNING FOR AGENTS:** Auto-generated secrets are **blocked in production**. The server will crash with a Zod validation error if `JWT_SECRET` or `REBASE_SERVICE_KEY` are not explicitly set when `NODE_ENV=production`.
400
-
401
- ### Production Validations
402
-
403
- When `NODE_ENV=production`, `loadEnv()` enforces these additional rules via Zod `.superRefine()`:
404
-
405
- | Rule | Error if violated |
406
- |------|-------------------|
407
- | **CORS required** | At least one of `CORS_ORIGINS` or `FRONTEND_URL` must be set |
408
- | **No auto-generated secrets** | `JWT_SECRET` and `REBASE_SERVICE_KEY` must be explicitly set |
409
- | **No localhost URLs** | All URL-type env vars are scanned — any containing `localhost`, `127.0.0.1`, or `::1` will fail validation (unless `ALLOW_LOCALHOST_IN_PRODUCTION=true`) |
410
-
411
- The localhost check applies to **all** string env vars (except `CORS_ORIGINS`) using a helper that parses URLs, custom protocols (e.g. `postgres://`), and plain `host:port` formats.
412
-
413
- ### `.env.example` Reference
414
-
415
- Copy the `.env.example` file as a starting point:
416
-
417
- ```bash
418
- cp .env.example .env
419
- ```
420
-
421
- The `.env.example` includes all variables with inline documentation. See `app/.env.example` in the repository.
422
-
423
- ### `.env.production` (Frontend Build)
424
-
425
- The `.env.production` file is read by Vite at build time to bake frontend config into the client bundle:
426
-
427
- ```bash
428
- # API URL: empty string = same-origin (backend + frontend share the same URL)
429
- VITE_API_URL=
430
-
431
- # Google OAuth Client ID (public — embedded in client bundle)
432
- VITE_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
433
- ```
434
-
435
- > **IMPORTANT FOR AGENTS:** `VITE_API_URL=` (empty) means same-origin — the frontend assumes the API is served from the same host. This works when using `serveSPA()` or a reverse proxy. Only set a full URL when the API is on a different domain.
436
-
437
- ---
438
-
439
- ## SPA Serving with `serveSPA()`
440
-
441
- In production, the backend can serve the frontend SPA directly, eliminating the need for a separate web server or CDN.
442
-
443
- ### `serveSPA()` Function Signature
444
-
445
- ```typescript
446
- import { serveSPA } from "@rebasepro/server-core";
447
-
448
- function serveSPA<E extends Env>(app: Hono<E>, config: ServeSPAConfig): void;
449
- ```
450
-
451
- ### `ServeSPAConfig` Options
452
-
453
- | Property | Type | Default | Description |
454
- |----------|------|---------|-------------|
455
- | `frontendPath` | `string` | — | **Required.** Absolute path to the frontend build directory |
456
- | `apiBasePath` | `string` | `"/api"` | Base path for API routes (excluded from SPA handling) |
457
- | `excludePaths` | `string[]` | `[]` | Additional paths to exclude from SPA handling (e.g. `["/health", "/ws", "/metrics"]`) |
458
- | `indexFile` | `string` | `"index.html"` | Index file to serve for SPA routes |
459
-
460
- ### How It Works
461
-
462
- 1. Serves static files from `frontendPath` using `@hono/node-server/serve-static`
463
- 2. For any GET request not matching `apiBasePath` or `excludePaths`, returns `index.html` (SPA fallback)
464
- 3. If `frontendPath` doesn't exist, logs a warning and **disables SPA serving** (does not crash)
465
- 4. If `index.html` is missing, passes through to the next handler
466
-
467
- ### Usage Example
468
-
469
- ```typescript
470
- import { serveSPA } from "@rebasepro/server-core";
471
- import path from "path";
472
-
473
- const isProduction = env.NODE_ENV === "production";
474
-
475
- // ... after initializeRebaseBackend() ...
476
-
477
- if (isProduction) {
478
- serveSPA(app, {
479
- frontendPath: path.resolve(process.cwd(), "../frontend/dist"),
480
- // apiBasePath defaults to "/api" — matches the default Rebase basePath
481
- // excludePaths: ["/health", "/ws"],
482
- });
483
- }
484
- ```
485
-
486
- > **IMPORTANT FOR AGENTS:** Call `serveSPA()` **after** `initializeRebaseBackend()` and after mounting the `/health` endpoint. The SPA catch-all route (`*`) must be the last route registered to avoid intercepting API or health check requests.
487
-
488
- ---
489
-
490
- ## AWS (ECS/Fargate + RDS)
491
-
492
- Deploy the Rebase Docker image to AWS using ECS (Fargate) with a managed PostgreSQL database via RDS.
493
-
494
- ### Architecture
495
-
496
- ```
497
- Internet → ALB (HTTPS) → ECS Fargate (Rebase container) → RDS PostgreSQL
498
- → S3 (file storage)
499
- ```
500
-
501
- ### Key Steps
502
-
503
- 1. **PostgreSQL** — Create an RDS PostgreSQL 16+ instance (or Aurora Serverless v2). Enable automated backups. Place in a private subnet.
504
- 2. **Docker Image** — Push the Rebase Docker image to ECR:
505
- ```bash
506
- # Build and tag
507
- docker build -t rebase-backend -f app/backend/Dockerfile .
508
- docker tag rebase-backend:latest <account-id>.dkr.ecr.<region>.amazonaws.com/rebase-backend:latest
509
-
510
- # Push
511
- aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account-id>.dkr.ecr.<region>.amazonaws.com
512
- docker push <account-id>.dkr.ecr.<region>.amazonaws.com/rebase-backend:latest
513
- ```
514
- 3. **ECS Task Definition** — Define a Fargate task with the container image, port `3001`, and environment variables (see env var reference above). Use AWS Secrets Manager for `JWT_SECRET`, `REBASE_SERVICE_KEY`, and `DATABASE_URL`.
515
- 4. **ALB** — Create an Application Load Balancer with HTTPS listener (ACM certificate). Target group pointing to the ECS service on port `3001`. Configure the health check path to `/health`.
516
- 5. **File Storage** — Set `STORAGE_TYPE=s3` with an S3 bucket. Grant the ECS task role `s3:GetObject`, `s3:PutObject`, `s3:DeleteObject` permissions.
517
-
518
- ### Key Environment Variables
519
-
520
- ```bash
521
- DATABASE_URL=postgresql://rebase:<password>@<rds-endpoint>:5432/rebase
522
- JWT_SECRET=<your-secret-min-32-chars>
523
- REBASE_SERVICE_KEY=<your-service-key-min-32-chars>
524
- CORS_ORIGINS=https://yourdomain.com
525
- FRONTEND_URL=https://yourdomain.com
526
- NODE_ENV=production
527
- STORAGE_TYPE=s3
528
- S3_BUCKET=your-rebase-uploads
529
- S3_REGION=us-east-1
530
- S3_ACCESS_KEY_ID=<iam-key-or-use-task-role>
531
- S3_SECRET_ACCESS_KEY=<iam-secret>
532
- ```
533
-
534
- > **TIP:** Use IAM task roles instead of static access keys for S3. Attach the policy to the ECS task execution role and omit `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` — the AWS SDK will use the role credentials automatically.
535
-
536
- ---
537
-
538
- ## GCP (Cloud Run + Cloud SQL)
539
-
540
- Deploy the Rebase Docker image to Cloud Run with Cloud SQL for PostgreSQL.
541
-
542
- ### Architecture
543
-
544
- ```
545
- Internet → Cloud Run (HTTPS, auto-scaling) → Cloud SQL PostgreSQL
546
- → GCS or S3-compatible (file storage)
547
- ```
548
-
549
- ### Key Steps
550
-
551
- 1. **PostgreSQL** — Create a Cloud SQL for PostgreSQL 16+ instance. Enable private IP or use the Cloud SQL Auth Proxy.
552
- 2. **Docker Image** — Push to Artifact Registry:
553
- ```bash
554
- # Build and tag
555
- docker build -t rebase-backend -f app/backend/Dockerfile .
556
- docker tag rebase-backend:latest <region>-docker.pkg.dev/<project-id>/rebase/backend:latest
557
-
558
- # Push
559
- gcloud auth configure-docker <region>-docker.pkg.dev
560
- docker push <region>-docker.pkg.dev/<project-id>/rebase/backend:latest
561
- ```
562
- 3. **Cloud Run Service** — Deploy with the Cloud SQL connection:
563
- ```bash
564
- gcloud run deploy rebase-backend \
565
- --image <region>-docker.pkg.dev/<project-id>/rebase/backend:latest \
566
- --region <region> \
567
- --port 3001 \
568
- --add-cloudsql-instances <project-id>:<region>:<instance-name> \
569
- --set-env-vars "NODE_ENV=production,CORS_ORIGINS=https://yourdomain.com,FRONTEND_URL=https://yourdomain.com" \
570
- --set-secrets "DATABASE_URL=rebase-db-url:latest,JWT_SECRET=rebase-jwt-secret:latest,REBASE_SERVICE_KEY=rebase-service-key:latest" \
571
- --min-instances 1 \
572
- --memory 512Mi \
573
- --allow-unauthenticated
574
- ```
575
- 4. **Custom Domain** — Map a custom domain in Cloud Run settings. Cloud Run provides HTTPS automatically.
576
- 5. **File Storage** — Use `STORAGE_TYPE=s3` with a GCS bucket via the S3-compatible interop endpoint, or use a dedicated S3 provider like Cloudflare R2.
577
-
578
- ### Cloud SQL Auth Proxy (Connection String)
579
-
580
- When using the Cloud SQL connector in Cloud Run, the database is exposed via a Unix socket:
581
-
582
- ```bash
583
- DATABASE_URL=postgresql://rebase:<password>@localhost/rebase?host=/cloudsql/<project-id>:<region>:<instance-name>
584
- ```
585
-
586
- > **WARNING:** Cloud Run has a **request timeout** (default 300s, max 3600s) and can scale to zero. WebSocket connections will be terminated when instances scale down. If you rely on Rebase realtime features, set `--min-instances 1` and increase the request timeout. For heavy realtime usage, consider GCE (Compute Engine) with Docker Compose instead.
587
-
588
- ---
589
-
590
- ## Azure (Container Apps + PostgreSQL Flexible Server)
591
-
592
- Deploy the Rebase Docker image to Azure Container Apps with Azure Database for PostgreSQL.
593
-
594
- ### Architecture
595
-
596
- ```
597
- Internet → Azure Container Apps (HTTPS, auto-scaling) → Azure Database for PostgreSQL
598
- → Azure Blob Storage (file storage)
599
- ```
600
-
601
- ### Key Steps
602
-
603
- 1. **PostgreSQL** — Create an Azure Database for PostgreSQL Flexible Server. Choose a Burstable or General Purpose tier. Place in an EU region (West Europe, North Europe, or France Central).
604
- 2. **Docker Image** — Push to Azure Container Registry (ACR):
605
- ```bash
606
- # Login to ACR
607
- az acr login --name YourRegistryName
608
-
609
- # Build and push
610
- docker build -t yourregistryname.azurecr.io/rebase-backend:latest -f app/backend/Dockerfile .
611
- docker push yourregistryname.azurecr.io/rebase-backend:latest
612
- ```
613
- 3. **Container App** — Create a Container Apps Environment and deploy:
614
- - Point to your ACR image
615
- - Set the target port to `3001`
616
- - Enable Ingress for external traffic
617
- - Configure environment variables (see below)
618
- 4. **Networking** — If the PostgreSQL server uses private networking, configure VNet integration in the Container Apps Environment.
619
- 5. **File Storage** — Use `STORAGE_TYPE=s3` with Azure Blob Storage via the S3-compatible API, or use Cloudflare R2.
620
-
621
- ### Key Environment Variables
622
-
623
- ```bash
624
- DATABASE_URL=postgresql://rebase_admin:<password>@<server-name>.postgres.database.azure.com:5432/rebase
625
- JWT_SECRET=<your-secret-min-32-chars>
626
- REBASE_SERVICE_KEY=<your-service-key-min-32-chars>
627
- CORS_ORIGINS=https://yourdomain.com
628
- FRONTEND_URL=https://yourdomain.com
629
- NODE_ENV=production
630
- ALLOW_REGISTRATION=false
631
- ```
632
-
633
- > **TIP:** Azure Container Apps provides built-in HTTPS with automatic TLS certificates. Use Managed Identity instead of static credentials for accessing Azure services.
634
-
635
- ---
636
-
637
- ## Scaleway (Serverless Containers + Managed PostgreSQL)
638
-
639
- Deploy the Rebase Docker image to Scaleway Serverless Containers. Scaleway is a premier European cloud provider with datacenters in Paris, Amsterdam, and Warsaw — ideal for EU data sovereignty.
640
-
641
- ### Architecture
642
-
643
- ```
644
- Internet → Scaleway Serverless Container (HTTPS) → Managed PostgreSQL
645
- → Object Storage (S3-compatible)
646
- ```
647
-
648
- ### Key Steps
649
-
650
- 1. **PostgreSQL** — Create a Managed Database for PostgreSQL in your preferred EU region (e.g., Paris `fr-par`).
651
- 2. **Docker Image** — Push to Scaleway Container Registry:
652
- ```bash
653
- # Build and push
654
- docker build -t rg.fr-par.scw.cloud/rebase-apps/rebase-backend:latest -f app/backend/Dockerfile .
655
- docker push rg.fr-par.scw.cloud/rebase-apps/rebase-backend:latest
656
- ```
657
- 3. **Serverless Container** — Deploy from the Scaleway Console or CLI:
658
- - Select your image from the Container Registry
659
- - Set the port to `3001`
660
- - Configure environment variables (see below)
661
- 4. **File Storage** — Use `STORAGE_TYPE=s3` with Scaleway Object Storage (natively S3-compatible):
662
- ```bash
663
- S3_ENDPOINT=https://s3.fr-par.scw.cloud
664
- S3_BUCKET=your-rebase-uploads
665
- S3_REGION=fr-par
666
- S3_FORCE_PATH_STYLE=true
667
- ```
668
-
669
- ### Key Environment Variables
670
-
671
- ```bash
672
- DATABASE_URL=postgresql://user:<password>@<instance-ip>:5432/rebase
673
- JWT_SECRET=<your-secret-min-32-chars>
674
- REBASE_SERVICE_KEY=<your-service-key-min-32-chars>
675
- CORS_ORIGINS=https://yourdomain.com
676
- FRONTEND_URL=https://yourdomain.com
677
- NODE_ENV=production
678
- ALLOW_REGISTRATION=false
679
- STORAGE_TYPE=s3
680
- S3_ENDPOINT=https://s3.fr-par.scw.cloud
681
- S3_BUCKET=your-rebase-uploads
682
- S3_REGION=fr-par
683
- S3_FORCE_PATH_STYLE=true
684
- ```
685
-
686
- > **TIP:** Scaleway Object Storage is natively S3-compatible — no interop layer needed. Set `S3_FORCE_PATH_STYLE=true` for compatibility.
687
-
688
- ---
689
-
690
- ## Hetzner (VPS + Docker Compose)
691
-
692
- The most cost-effective production deployment. A single Hetzner VPS running Docker Compose.
693
-
694
- ### Architecture
695
-
696
- ```
697
- Internet → Caddy (HTTPS, auto-TLS) → Rebase container (port 3001)
698
- → PostgreSQL container
699
- → Hetzner Volume (persistent storage)
700
- ```
701
-
702
- ### Setup
703
-
704
- 1. **Provision a VPS** — A Hetzner CPX21 (3 vCPU, 4 GB RAM, ~€8/mo) handles most workloads. Choose Ubuntu 24.04.
705
- 2. **Install Docker** — SSH in and install Docker + Docker Compose:
706
- ```bash
707
- curl -fsSL https://get.docker.com | sh
708
- ```
709
- 3. **Clone your project** and copy your `.env` file to the server.
710
- 4. **Use the existing `docker-compose.yml`** — the template generated by `rebase init` works out of the box. Just update `.env` with production values:
711
- ```bash
712
- DATABASE_PASSWORD=<strong-random-password>
713
- JWT_SECRET=<your-secret-min-32-chars>
714
- REBASE_SERVICE_KEY=<your-service-key-min-32-chars>
715
- CORS_ORIGINS=https://yourdomain.com
716
- FRONTEND_URL=https://yourdomain.com
717
- NODE_ENV=production
718
- ALLOW_REGISTRATION=false
719
- ```
720
- 5. **Reverse Proxy (Caddy)** — Add a Caddy service for automatic HTTPS:
721
- ```yaml
722
- # Add to docker-compose.yml
723
- caddy:
724
- image: caddy:2-alpine
725
- restart: unless-stopped
726
- ports:
727
- - "80:80"
728
- - "443:443"
729
- - "443:443/udp" # HTTP/3
730
- volumes:
731
- - ./Caddyfile:/etc/caddy/Caddyfile
732
- - caddy_data:/data
733
- - caddy_config:/config
734
- depends_on:
735
- - backend
736
-
737
- # Add to volumes:
738
- caddy_data:
739
- driver: local
740
- caddy_config:
741
- driver: local
742
- ```
743
-
744
- Create a `Caddyfile`:
745
- ```
746
- yourdomain.com {
747
- reverse_proxy backend:3001
748
- }
749
- ```
750
- 6. **Start everything:**
751
- ```bash
752
- docker compose up -d
753
- ```
754
- 7. **Persistent Storage** — Attach a Hetzner Volume for the `postgres_data` and `uploads` Docker volumes if you need data to survive server rebuilds.
755
-
756
- ### Backups
757
-
758
- Schedule automated PostgreSQL backups via cron on the host:
759
-
760
- ```bash
761
- # /etc/cron.d/rebase-backup
762
- 0 3 * * * root docker compose -f /path/to/docker-compose.yml exec -T db pg_dump -U rebase rebase | gzip > /backups/rebase-$(date +\%Y\%m\%d).sql.gz
763
- ```
764
-
765
- > **TIP:** Hetzner also offers managed snapshots (server-level) and the option to attach a Hetzner Volume for data that survives server rebuilds. For production, strongly consider both.
766
-
767
- ---
768
-
769
- ## PaaS (Railway, Render, Fly.io)
770
-
771
- Docker-based PaaS platforms that deploy directly from your repo or Docker image.
772
-
773
- ### General Pattern
774
-
775
- All PaaS platforms follow the same workflow:
776
- 1. Connect your Git repository or point to a Dockerfile
777
- 2. Provision a managed PostgreSQL add-on
778
- 3. Set environment variables (see env var reference above)
779
- 4. Deploy — the platform builds and runs the Docker image
780
-
781
- ### Platform-Specific Notes
782
-
783
- | Platform | PostgreSQL | Notes |
784
- |----------|-----------|-------|
785
- | **Railway** | Built-in add-on | Connects via `DATABASE_URL` injected automatically. Supports persistent volumes for file uploads. |
786
- | **Render** | Managed PostgreSQL | Use a "Web Service" with Docker runtime. Free tier has cold starts — use paid for production. |
787
- | **Fly.io** | Fly Postgres (community) | Closest to self-hosted — Fly Postgres is a managed wrapper around standard Postgres. Supports persistent volumes via `fly volumes`. |
788
-
789
- ### Minimum Environment Variables
790
-
791
- ```bash
792
- DATABASE_URL=<provided-by-platform>
793
- JWT_SECRET=<your-secret-min-32-chars>
794
- REBASE_SERVICE_KEY=<your-service-key-min-32-chars>
795
- CORS_ORIGINS=https://your-app.up.railway.app # or your custom domain
796
- FRONTEND_URL=https://your-app.up.railway.app
797
- NODE_ENV=production
798
- ALLOW_REGISTRATION=false
799
- ```
800
-
801
- > **WARNING:** Most PaaS free tiers have ephemeral filesystems — uploaded files will be lost on redeploy. Use `STORAGE_TYPE=s3` with an external object storage provider (Cloudflare R2, AWS S3, MinIO) for production file storage.
802
-
803
- ---
804
-
805
- ## Health Check Endpoint
806
-
807
- The Docker `HEALTHCHECK` instruction hits `/health`. Mount it in your backend entry:
808
-
809
- ```typescript
810
- app.get("/health", async (c) => {
811
- const result = await backend.healthCheck();
812
- const status = result.healthy ? 200 : 503;
813
- return c.json({
814
- status: result.healthy ? "ok" : "degraded",
815
- latencyMs: result.latencyMs,
816
- ...(result.details ? { details: result.details } : {})
817
- }, status);
818
- });
819
- ```
820
-
821
- `healthCheck()` runs `SELECT 1` against the database and returns latency. Returns `{ healthy: boolean, latencyMs: number, details?: { error: string } }`.
822
-
823
- ---
824
-
825
- ## Graceful Shutdown
826
-
827
- The `RebaseBackendInstance` exposes a `shutdown()` method for clean container termination:
828
-
829
- ```typescript
830
- const backend = await initializeRebaseBackend({ ... });
831
-
832
- const gracefulShutdown = async (signal: string) => {
833
- await backend.shutdown(); // Stops cron, realtime, drains HTTP (15s timeout)
834
- await postgresResources.pool.end(); // Close database pool
835
- process.exit(0);
836
- };
837
-
838
- process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
839
- process.on("SIGINT", () => gracefulShutdown("SIGINT"));
840
- ```
841
-
842
- `shutdown(timeoutMs?: number)`:
843
- - Default timeout: `15000` ms
844
- - Stops cron scheduler
845
- - Destroys realtime services (LISTEN clients, debounce timers)
846
- - Closes HTTP server and drains in-flight requests
847
- - Pass `0` to skip the force-exit timer (useful in tests)
848
-
849
- > **WARNING FOR AGENTS:** Do NOT call `server.close()` separately when using `backend.shutdown()` — it already closes the HTTP server internally. Calling `server.close()` twice will deadlock.
850
-
851
- ---
852
-
853
- ## ⛔ Agent Deployment Rules
854
-
855
- **Agents should NEVER deploy or run deployment commands unless explicitly asked by the user in the current conversation.** This includes:
856
- - `rebase deploy` (any variant)
857
- - `gcloud run deploy`
858
- - `terraform apply` (any variant that deploys resources)
859
- - `docker compose up` in production
860
- - Any command targeting staging or production environments
861
-
862
- **What agents CAN do:**
863
- - Edit source code
864
- - Run builds (`pnpm run build`)
865
- - Run tests (`pnpm test`)
866
- - Run local dev server (`pnpm dev`)
867
- - Check logs (read-only)
868
- - Create or edit Dockerfiles and docker-compose files
869
- - Create or edit `.env` files
870
- - Run deployment commands *only* if the user explicitly asks you to deploy in the current conversation. Otherwise, provide the exact commands for the user to run.
871
-
872
- ---
873
-
874
- ## References
875
-
876
- - **Documentation:** [rebase.pro/docs](https://rebase.pro/docs)
877
- - **GitHub:** [github.com/rebasepro/rebase](https://github.com/rebasepro/rebase)
878
- - **Dockerfile:** `app/backend/Dockerfile`
879
- - **Docker Compose (monorepo):** `app/backend/docker-compose.yml`
880
- - **Docker Compose (template):** `packages/cli/templates/template/docker-compose.yml`
881
- - **Entrypoint:** `app/backend/entrypoint.sh`
882
- - **Env Schema:** `packages/server-core/src/env.ts`
883
- - **serveSPA:** `packages/server-core/src/serve-spa.ts`
884
- - **Backend Entry:** `app/backend/src/index.ts`
885
- - **.env.example:** `app/.env.example`