# nextgin — Complete Documentation (llms-full.txt) > Next.js App Router frontend paired with a zero-dependency pure-Go (`net/http`) API and in-process cron backend. > Website: https://next-gin.dev | Go module: github.com/Chidi09/nextgin | npm: @nextgin/adapter | Repo: https://github.com/Chidi09/nextgin --- # Getting Started with nextgin **Next.js App Router on the frontend. Pure-Go (`net/http`) API & cron backend.** Zero external Go dependencies · ~7.5 MB native binary · Deploy split or all-in-one. - Go module: [`github.com/Chidi09/nextgin`](https://pkg.go.dev/github.com/Chidi09/nextgin) - npm adapter & CLI: [`@nextgin/adapter`](https://www.npmjs.com/package/@nextgin/adapter) - Source & examples: [`Chidi09/nextgin`](https://github.com/Chidi09/nextgin) --- ## Why nextgin? Keep Next.js focused on what it does best — **UI, SSR, RSC, and Server Actions** — while a tiny, zero-dependency Go binary owns your **hot path and background jobs**: auth, sessions, rate limiting, payments, webhooks, and sub-minute crons. - **Zero external Go dependencies:** Built purely on Go 1.22+ `net/http.ServeMux` with `Group`, `With`, `Middleware`, panic recovery, JSON/raw-body helpers (`ReadJSON`, `ReadRawBody`, `WriteJSON`), per-IP `RateLimit`, and secure `SetSessionCookie` / `ClearSessionCookie`. - **Crons are authenticated HTTP routes:** `app.Cron("name", "*/5 * * * *", handler)` registers `/_nextgin/cron/` behind fail-closed auth and runs in-process on `backend` / `selfhost` (no daily-cron limits), with graceful `SIGTERM` cancellation and an optional `CronLocker` hook for multi-replica deploys. - **One codebase, any topology:** Ship as a split stack (Next.js on Vercel or Cloudflare Pages + Go container on Cloudflare Containers, Fly.io, Cloud Run, Railway, or a VPS) or self-host everything behind a single Go binary (`nextgin deploy`). - **Go is the front door on self-host:** Serves static assets, prerendered pages, `next.config` headers/redirects, and API routes natively, proxying only dynamic SSR/RSC/Server Action requests to Node or Bun workers over Unix sockets. - **Built-in liveness probe:** `GET /_nextgin/health` responds `200 {"status":"ok"}` without touching Next.js or polluting exported routes. --- ## Quick Start Scaffold a new project with a clean 3-layer Go layout (`internal/domain`, `store`, `service`, `httpapi`) and a typed Next.js API client (`lib/api.ts`): ```bash # Single-repo self-host layout npx @nextgin/adapter init my-app # Split layout (web/ + backend/) for Vercel / Cloudflare Pages + Go container npx @nextgin/adapter init my-app --layout split ``` Or add `nextgin` to an existing Next.js app: ```bash go get github.com/Chidi09/nextgin npm install @nextgin/adapter ``` ```js // next.config.mjs import { createNextGinAdapter } from '@nextgin/adapter' export default { adapterPath: createNextGinAdapter(), } ``` Run locally with live reload for both Next.js and Go: ```bash nextgin dev # Next.js dev server + Go backend with auto-restart on .go changes nextgin build # next build, finalize .nextgin manifest, go build -o server ./server ``` --- ## A Complete Go Backend in One File ```go package main import ( "log" "net/http" "os" "github.com/Chidi09/nextgin" ) func main() { app, err := nextgin.New("./.nextgin", nextgin.Config{ TrustForwardedHeaders: true, }) if err != nil { log.Fatal(err) } app.Router.Use(nextgin.CORS("https://example.com")) api := app.Router.Group("/api") authLimit := nextgin.RateLimitWithConfig(nextgin.RateLimitConfig{ RPS: 2, Burst: 10, TrustForwardedHeaders: true, }) api.POST("/login", func(w http.ResponseWriter, r *http.Request) { var body struct{ Email, Password string } if err := nextgin.ReadJSON(r, &body); err != nil { nextgin.WriteError(w, http.StatusBadRequest, "invalid json") return } // Verify credentials and issue a session token... nextgin.SetSessionCookie(w, "sid", "token", nextgin.CookieOptions{ Domain: ".example.com", MaxAge: 7 * 86400, }) nextgin.WriteJSON(w, http.StatusOK, map[string]bool{"ok": true}) }, authLimit) api.POST("/logout", func(w http.ResponseWriter, r *http.Request) { nextgin.ClearSessionCookie(w, "sid", nextgin.CookieOptions{Domain: ".example.com"}) w.WriteHeader(http.StatusNoContent) }) // Read raw bytes first so HMAC webhook signatures verify cleanly. api.POST("/webhooks/pay", func(w http.ResponseWriter, r *http.Request) { raw, err := nextgin.ReadRawBody(w, r, 256<<10) if err != nil { nextgin.WriteError(w, http.StatusBadRequest, "invalid body") return } _ = raw // verify signature with your payment provider w.WriteHeader(http.StatusOK) }) // Unlimited crons — runs in-process in Go, cancelled cleanly on SIGTERM. app.Cron("expire-carts", "* * * * *", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) app.MountFrontend() // no-op when NEXTGIN_TARGET=backend log.Fatal(app.Run(":" + os.Getenv("PORT"))) } ``` --- ## Deployment Targets | Target | Command | Where it runs | Best for | |---|---|---|---| | **Split (Recommended)** | `nextgin build --web-target vercel --backend-target container --backend-url https://api.example.com` | Next.js on Vercel / Cloudflare Pages + Go container on Cloudflare Containers, Fly.io, Cloud Run, Railway, or VPS | Zero serverless API/cron invocations, full DB connection pooling, sub-minute crons | | **Self-Host / VPS** | `nextgin deploy --host root@203.0.113.7 --domain shop.example.com` | Single VPS with Go binary + Node/Bun workers + Postgres/Redis + Caddy HTTPS | Predictable flat-rate hosting with one-command SSH deploys | | **Vercel (Combined)** | `nextgin build --target vercel` | Next.js + Go service both on Vercel | Single-dashboard deploys (pass `--vercel-hobby` for daily crons) | ### Split Mode Notes - `--api-mode direct` *(default)*: The browser calls `NEXT_PUBLIC_NEXTGIN_API_URL` directly so API traffic bypasses frontend bandwidth/compute. Pair with `nextgin.CORS(...)` and parent-domain cookies (`Domain: ".example.com"`). - `--api-mode rewrite`: Opt-in same-origin mode that writes external rewrites into `web/vercel.json`. - Protect server-to-server routes called from SSR or Server Actions with `nextgin.RequireInternal()` and `NEXTGIN_INTERNAL_SECRET`. - For multi-replica deploys, plug a Postgres advisory lock or Redis `SET NX` into `Config.CronLocker` (or set `NEXTGIN_SCHEDULER=off` on replicas). ### Single-VPS Deploy Notes - Postgres and Redis are auto-detected from `go.mod`. First deploy prompts once per service to either provision it on the VPS or use an external URL; generated secrets live in `/opt/nextgin//.env` (`0600`) and persist across redeploys. - Use `nextgin deploy --local` to run locally, or `--dry-run` to inspect generated files in `.nextgin/deploy/`. ### Cloudflare (Pages + Containers) You can also run the entire stack on Cloudflare (this is how `next-gin.dev` itself is deployed): - **Backend (`NEXTGIN_TARGET=backend`):** Cross-compile a stripped `linux/amd64` Go binary (~7.5 MB) into a minimal Alpine image and deploy it to **Cloudflare Containers** (`instance_type: "lite"`, 256 MiB) behind a custom domain (`api.example.com`). - **Frontend:** Deploy the Next.js app to **Cloudflare Pages**, either calling `https://api.example.com` directly or proxying `/api/*` through a Pages Function (`functions/api/[[path]].js`) to `NEXTGIN_BACKEND_URL`. - **Crons:** Wire Cloudflare Worker `triggers.crons` to `POST /_nextgin/cron/` with `Authorization: Bearer $CRON_SECRET` so scheduled jobs wake the container reliably even when it sleeps. See the full copy-pasteable `Dockerfile`, `wrangler.jsonc`, and Worker wrapper in [docs/COOKBOOK.md](docs/COOKBOOK.md#7-deploying-on-cloudflare-pages--containers). --- ## Security & Hardening Defaults - **Strict body limits:** `ReadJSON` caps request bodies at 1 MiB (`DefaultMaxBodyBytes`) and rejects trailing JSON tokens. Use `ReadJSONLimit` or `ReadRawBody` for custom limits and HMAC webhooks. - **Streaming-safe timeouts:** `backend` and `vercel` targets enforce `ReadHeaderTimeout: 10s`, `ReadTimeout: 15s`, `WriteTimeout: 30s`, `IdleTimeout: 60s`. `selfhost` keeps `WriteTimeout: 0` so Next.js Suspense and SSE streams are never cut off. - **Fail-closed by default:** Cron routes require the process-internal bearer token or `CRON_SECRET`; `RequireInternal` returns `401` whenever `NEXTGIN_INTERNAL_SECRET` is unset; `CORS` panics on empty or `*` origins; `SetSessionCookie` defaults to `HttpOnly: true`, `Secure: true`, `SameSite: Lax`. --- ## Examples & Documentation | Resource | Description | |---|---| | [examples/fullstack-app](examples/fullstack-app) | Minimal Next.js App Router + Go API, SSR, Server Actions, and end-to-end test suite | | [examples/ecommerce-app](examples/ecommerce-app) | Full SQLite store with auth, rate limiting, cart, transactional checkout, HMAC webhook, and 1-minute cart-expiry cron | | [docs/PATTERNS.md](docs/PATTERNS.md) | App folder structure, `httpapi → service → store` layering, error mapping, middleware, and Next.js ↔ Go client boundary | | [docs/COOKBOOK.md](docs/COOKBOOK.md) | Deployment topologies, database/ORM ownership (`sqlc`), auth, webhooks, and distributed cron locking | | [docs/SPEC.md](docs/SPEC.md) | Architecture specification, design decisions, and benchmarks | | [AGENTS.md](AGENTS.md) | Contributor and AI coding agent guide | --- ## Development ```bash gofmt -l . go vet ./... go test -race -count=1 ./... (cd packages/adapter && npx tsc -p tsconfig.json && node --test test/) npm run build -w fullstack-app && scripts/e2e.sh node && scripts/e2e.sh bun ``` ## License [MIT](LICENSE) --- # App Architecture & Code Patterns How to structure a real `nextgin` application, write clean Go HTTP APIs, separate concerns without over-engineering, and keep the Next.js ↔ Go boundary crisp. > **Reference implementation:** See [`examples/ecommerce-app/`](../examples/ecommerce-app/) for a complete working app following every pattern in this guide (`internal/domain`, `internal/store`, `internal/service`, `internal/httpapi`, `lib/api.ts`, and `httptest` API tests). --- ## 1. Directory Layout Keep `main.go` thin (wiring only) and place application code under `internal/` so Go's compiler enforces encapsulation. ### Split Repo (`web/` + `backend/` — Recommended for Vercel + Container) ```text my-app/ ├── web/ # Next.js App Router (UI, SSR, RSC) │ ├── app/ │ │ ├── (store)/ # Route groups for UI pages │ │ └── products/[id]/page.tsx │ ├── components/ # Client & Server UI components │ ├── lib/ │ │ ├── api.ts # Typed client for Go API (browser + server) │ │ └── types.ts # Shared API response/request types │ └── next.config.mjs └── backend/ # Pure-Go nextgin API + cron service ├── cmd/server/main.go # Config loading, DI wiring, app.Run() ├── migrations/ # Numbered SQL migrations (001_init.sql, ...) ├── internal/ │ ├── domain/ # Shared domain types & sentinel errors │ ├── store/ # SQL queries (sqlc / database/sql / pgx) │ ├── service/ # Business logic & transaction boundaries │ ├── httpapi/ # HTTP handlers, DTOs, validation, middleware │ └── cronjobs/ # Scheduled job handlers └── go.mod ``` ### Single-Repo Self-Host (`nextgin build` / `nextgin deploy`) Same Go `internal/` layout at the repo root alongside `app/`, `components/`, and `lib/`: ```text my-app/ ├── main.go # Thin entrypoint (wires internal/* + app.MountFrontend()) ├── internal/ │ ├── domain/ │ ├── store/ │ ├── service/ │ ├── httpapi/ │ └── cronjobs/ ├── migrations/ ├── app/ # Next.js App Router ├── lib/api.ts ├── next.config.mjs └── go.mod ``` > **Rule of thumb for small apps:** If a feature has trivial CRUD, you don't need separate `service` and `store` packages on day one — a single `internal/orders` package with `store.go` + `handler.go` is cleaner than empty pass-through layers. Introduce `service/` when an operation spans multiple tables, external APIs, or transactions (e.g., checkout, billing, auth). --- ## 2. Separation of Concerns (The 3-Layer Rule) Each layer has **one job** and strict dependency direction: `httpapi → service → store → DB`. | Layer | Owns | Must NOT Do | |---|---|---| | **`main.go`** | Reading env/config, opening DB pool, constructing stores/services/handlers, registering routes & crons, calling `app.Run`. | Contain SQL, business rules, or inline handler logic (beyond trivial health/ping). | | **`httpapi`** | Parsing HTTP (`r.PathValue`, `ReadJSON`, cookies, headers), validating input shape, calling a service, mapping domain errors to HTTP status codes, writing JSON/cookies. | Run SQL directly, open DB transactions, or import `database/sql`. | | **`service`** | Business rules, authorization checks ("can user X cancel order Y?"), DB transactions, calling third-party APIs (Stripe, email), idempotency. | Know about `http.Request`, `http.ResponseWriter`, status codes, or cookies. | | **`store`** | Parameterized SQL (`sqlc` or `pgx`/`database/sql`), scanning rows into domain structs, translating DB errors (e.g., `sql.ErrNoRows` → `domain.ErrNotFound`, unique violation → `domain.ErrConflict`). | Make HTTP calls, format JSON responses, or enforce HTTP auth. | --- ## 3. Writing Clean Go API Handlers ### Struct-Based Handlers (No Package Globals) Group related endpoints onto a handler struct that takes its dependencies explicitly via a constructor. Register routes in a single `RegisterRoutes` method: ```go package httpapi import ( "net/http" "github.com/Chidi09/nextgin" ) type OrderHandler struct { orders OrderService // narrow interface, easy to mock in unit tests } func NewOrderHandler(orders OrderService) *OrderHandler { return &OrderHandler{orders: orders} } func (h *OrderHandler) Register(r *nextgin.Router, requireAuth nextgin.Middleware) { orders := r.Group("/orders", requireAuth) orders.GET("", handle(h.List)) orders.POST("", handle(h.Create)) orders.GET("/{id}", handle(h.Get)) orders.POST("/{id}/cancel", handle(h.Cancel)) } ``` ### Centralized Error Handling (`handle` Wrapper) Standard `http.HandlerFunc` forces repetitive `if err != nil { WriteError(...); return }` blocks and makes it easy to accidentally leak `sql.ErrNoRows` or raw SQL errors to clients. Instead, define domain errors in `internal/domain/errors.go`: ```go package domain import "errors" var ( ErrNotFound = errors.New("not found") ErrConflict = errors.New("conflict") ErrUnauthorized = errors.New("unauthorized") ErrForbidden = errors.New("forbidden") ErrInsufficientStock = errors.New("insufficient stock") ) type ValidationError struct { Fields map[string]string } func (e ValidationError) Error() string { return "validation failed" } ``` Then write one small adapter in `internal/httpapi/respond.go`: ```go package httpapi import ( "errors" "log" "net/http" "github.com/Chidi09/nextgin" "myapp/internal/domain" ) type handlerFunc func(w http.ResponseWriter, r *http.Request) error func handle(fn handlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if err := fn(w, r); err != nil { writeDomainError(w, r, err) } } } func writeDomainError(w http.ResponseWriter, r *http.Request, err error) { var valErr domain.ValidationError switch { case errors.As(err, &valErr): nextgin.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{ "error": "validation failed", "fields": valErr.Fields, }) case errors.Is(err, nextgin.ErrBodyTooLarge): nextgin.WriteError(w, http.StatusRequestEntityTooLarge, "request body too large") case errors.Is(err, domain.ErrNotFound): nextgin.WriteError(w, http.StatusNotFound, "resource not found") case errors.Is(err, domain.ErrConflict): nextgin.WriteError(w, http.StatusConflict, "resource already exists") case errors.Is(err, domain.ErrUnauthorized): nextgin.WriteError(w, http.StatusUnauthorized, "unauthorized") case errors.Is(err, domain.ErrForbidden): nextgin.WriteError(w, http.StatusForbidden, "forbidden") case errors.Is(err, domain.ErrInsufficientStock): nextgin.WriteError(w, http.StatusConflict, err.Error()) default: // Never leak internal or SQL errors to clients; log them server-side. log.Printf("http error %s %s: %v", r.Method, r.URL.Path, err) nextgin.WriteError(w, http.StatusInternalServerError, "internal server error") } } ``` Now every handler stays linear, readable, and leak-free: ```go func (h *OrderHandler) Get(w http.ResponseWriter, r *http.Request) error { user := UserFromContext(r.Context()) id := r.PathValue("id") order, err := h.orders.GetForUser(r.Context(), user.ID, id) if err != nil { return err } nextgin.WriteJSON(w, http.StatusOK, toOrderResponse(order)) return nil } ``` ### Request DTOs & Explicit Validation Never unmarshal HTTP JSON directly into database/domain structs (prevents mass-assignment bugs like a client sending `"role": "admin"` or `"status": "paid"`). Use dedicated request structs with a `Validate()` method: ```go type createOrderRequest struct { ShippingAddress string `json:"shippingAddress"` CouponCode string `json:"couponCode"` } func (req createOrderRequest) Validate() error { fields := map[string]string{} if strings.TrimSpace(req.ShippingAddress) == "" { fields["shippingAddress"] = "required" } if len(req.CouponCode) > 32 { fields["couponCode"] = "must be 32 characters or fewer" } if len(fields) > 0 { return domain.ValidationError{Fields: fields} } return nil } func (h *OrderHandler) Create(w http.ResponseWriter, r *http.Request) error { var req createOrderRequest if err := nextgin.ReadJSON(r, &req); err != nil { if errors.Is(err, nextgin.ErrBodyTooLarge) { return err } return domain.ValidationError{Fields: map[string]string{"body": "invalid JSON"}} } if err := req.Validate(); err != nil { return err } user := UserFromContext(r.Context()) order, err := h.orders.Checkout(r.Context(), user.ID, req.ShippingAddress, req.CouponCode) if err != nil { return err } nextgin.WriteJSON(w, http.StatusCreated, toOrderResponse(order)) return nil } ``` ### Consistent Response & Pagination Shapes Pick one JSON convention across all endpoints and stick to it: - **Single resource:** return the object directly (`{"id": "...", "status": "paid"}`). - **Collections:** always wrap in an object (`{"items": [...], "nextCursor": "..."}`) — never a bare top-level JSON array, so you can add pagination or metadata later without breaking clients. - **Mutations with no body:** `w.WriteHeader(http.StatusNoContent)` (`204`). - **Errors:** `{"error": "message"}` (from `nextgin.WriteError`) plus optional `"fields": {...}` for validation errors. - **Money:** store and return integer minor units (`priceCents: 2999`, `currency: "USD"`), never floats. --- ## 4. Middleware & Typed Request Context ### Private Context Keys Never use raw strings (`"user"`) as `context.WithValue` keys. Define unexported struct types and typed accessors: ```go package httpapi import ( "context" "net/http" "github.com/Chidi09/nextgin" "myapp/internal/domain" ) type userCtxKey struct{} func withUser(ctx context.Context, u domain.User) context.Context { return context.WithValue(ctx, userCtxKey{}, u) } func UserFromContext(ctx context.Context) domain.User { u, _ := ctx.Value(userCtxKey{}).(domain.User) return u } func RequireAuth(sessions SessionService) nextgin.Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := r.Cookie("sid") if err != nil || c.Value == "" { nextgin.WriteError(w, http.StatusUnauthorized, "sign in required") return } user, err := sessions.Resolve(r.Context(), c.Value) if err != nil { nextgin.WriteError(w, http.StatusUnauthorized, "invalid session") return } next.ServeHTTP(w, r.WithContext(withUser(r.Context(), user))) }) } } ``` ### Scoped Middleware Composition Attach middleware at the **narrowest scope** that needs it: ```go // 1. Global (every Go route): request logging, recovery, CORS (split mode only) app.Router.Use(requestLogger) if origin := os.Getenv("CORS_ORIGIN"); origin != "" { app.Router.Use(nextgin.CORS(origin)) } // 2. Public API group api := app.Router.Group("/api") productHandler.Register(api) // 3. Per-route middleware for tight rate limits authLimit := nextgin.RateLimitWithConfig(nextgin.RateLimitConfig{ RPS: 2, Burst: 10, TrustForwardedHeaders: cfg.TrustProxy, }) api.POST("/auth/login", handle(authHandler.Login), authLimit) api.POST("/auth/register", handle(authHandler.Register), authLimit) // 4. Authenticated group authed := api.Group("", RequireAuth(sessionSvc)) orderHandler.Register(authed) cartHandler.Register(authed) // 5. Internal server-to-server group (Next.js SSR -> Go) internal := app.Router.Group("/internal", nextgin.RequireInternal()) internal.GET("/users/{id}/summary", handle(userHandler.InternalSummary)) ``` --- ## 5. Transactions, Context & Idempotency ### Always Propagate `r.Context()` Every service and store method takes `ctx context.Context` as its first parameter and passes it to `db.QueryContext` / `db.ExecContext` / `http.NewRequestWithContext`. When a browser cancels a request or `SIGTERM` shuts down a cron job, in-flight DB queries cancel immediately instead of piling up connections. ### Keep Transactions Inside the Service/Store Layer HTTP handlers should never call `db.BeginTx`. Wrap multi-step mutations (like checkout: verify stock → decrement inventory → insert order → clear cart) in one atomic transaction helper inside `service` or `store`: ```go func (s *OrderService) Checkout(ctx context.Context, userID, addr, coupon string) (domain.Order, error) { var order domain.Order err := s.tx.WithinTx(ctx, func(ctx context.Context, q store.Querier) error { items, err := q.ListCartItems(ctx, userID) if err != nil { return err } if len(items) == 0 { return domain.ValidationError{Fields: map[string]string{"cart": "is empty"}} } // Decrement stock with atomic guard: // UPDATE products SET stock = stock - $1 WHERE id = $2 AND stock >= $1 // ... order, err = q.CreateOrder(ctx, userID, addr, items) if err != nil { return err } return q.ClearCart(ctx, userID) }) return order, err } ``` ### Idempotency for Payments & Webhooks - **Webhooks:** store the provider's event ID in a `processed_webhook_events(event_id PRIMARY KEY)` table inside the same transaction as the state transition (`UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending'`). Duplicate deliveries become safe no-ops. - **Checkout / mutations:** accept an optional `Idempotency-Key` header from the client on retryable `POST` endpoints (`POST /api/orders`). --- ## 6. Frontend ↔ Backend Boundary (Next.js ↔ Go) ### Where Does Each Piece Live? | Concern | Put It In | Why | |---|---|---| | Auth, sessions, RBAC, rate limiting | **Go (`httpapi` + `service`)** | Hot path, fail-closed cookies, zero Node overhead. | | Cart, checkout, payments, webhooks | **Go (`service` + `store`)** | Transactional integrity, raw-body HMAC verification, DB pooling. | | Scheduled jobs & cleanup | **Go (`app.Cron`)** | In-process scheduler, graceful `SIGTERM`, no Vercel Cron limits. | | Page layout, SEO, SSR, streaming | **Next.js Server Components** | Native App Router strengths. | | Interactive forms, optimistic UI | **Next.js Client Components** | Calls Go `/api/*` via `lib/api.ts`. | | Form mutations that need `revalidatePath` / `revalidateTag` | **Next.js Server Action → Go `/internal/*`** | Thin Server Action forwards to Go over `NEXTGIN_INTERNAL_URL`, then revalidates Next.js cache. | ### One Typed Client Module (`lib/api.ts`) Avoid scattering raw `fetch("/api/...")` calls across components. Centralize base URLs, cookies, internal headers, and error parsing in `lib/api.ts`: ```ts // web/lib/api.ts export class ApiError extends Error { constructor( public status: number, message: string, public fields?: Record, ) { super(message) } } const PUBLIC_BASE = process.env.NEXT_PUBLIC_NEXTGIN_API_URL ?? '' /** Use in Client Components (browser). Sends HttpOnly session cookies automatically. */ export async function apiFetch(path: string, init?: RequestInit): Promise { const res = await fetch(`${PUBLIC_BASE}${path}`, { ...init, credentials: 'include', headers: { ...(init?.body ? { 'Content-Type': 'application/json' } : {}), ...init?.headers, }, }) return parseResponse(res) } /** Use in Server Components & Server Actions only. Calls Go directly over loopback/internal URL. */ export async function internalFetch(path: string, init?: RequestInit): Promise { const base = process.env.NEXTGIN_INTERNAL_URL ?? 'http://127.0.0.1:8080' const res = await fetch(`${base}${path}`, { ...init, cache: init?.cache ?? 'no-store', headers: { 'X-Nextgin-Internal': process.env.NEXTGIN_INTERNAL_SECRET ?? '', ...(init?.body ? { 'Content-Type': 'application/json' } : {}), ...init?.headers, }, }) return parseResponse(res) } async function parseResponse(res: Response): Promise { if (res.status === 204) return undefined as T const data = await res.json().catch(() => ({})) if (!res.ok) { throw new ApiError(res.status, data.error ?? res.statusText, data.fields) } return data as T } ``` --- ## 7. Testing Patterns Because Go owns the API and business logic, you can test the entire backend in milliseconds with `go test -race ./...` — **no Node process or Next.js build required**. ### Handler Unit Tests (`httptest`) Mount your handlers onto a fresh `nextgin.New("", nextgin.Config{})` (with `NEXTGIN_TARGET=backend` so no frontend build is needed) and hit `app.Router.ServeHTTP`: ```go func TestCreateOrder_ValidationError(t *testing.T) { t.Setenv("NEXTGIN_TARGET", "backend") app, err := nextgin.New("", nextgin.Config{}) if err != nil { t.Fatal(err) } h := httpapi.NewOrderHandler(&fakeOrderService{}) h.Register(app.Router.Group("/api"), fakeAuthMiddleware(domain.User{ID: "u1"})) req := httptest.NewRequest(http.MethodPost, "/api/orders", strings.NewReader(`{"shippingAddress":""}`)) rec := httptest.NewRecorder() app.Router.ServeHTTP(rec, req) if rec.Code != http.StatusUnprocessableEntity { t.Fatalf("got status %d, want 422: %s", rec.Code, rec.Body.String()) } } ``` ### Store & Integration Tests - **SQLite apps:** run migrations against `file::memory:?cache=shared` (or `t.TempDir()/test.db`) per test so tests run in parallel with `-race`. - **Postgres apps:** create an isolated schema or transaction per test that rolls back on `t.Cleanup`. - **Cron jobs:** invoke your cron handler directly via `httptest` (or test the underlying service method) and pass a cancellable `context.WithCancel` to verify graceful shutdown. --- ## 8. Anti-Patterns to Avoid | Don't Do This | Do This Instead | |---|---| | Putting all routes, SQL, and helpers in `main.go` | Keep `main.go` as wiring; split `httpapi`, `service`, `store`, `domain` under `internal/`. | | Returning `err.Error()` directly from `sql.DB` to `WriteError` | Map `sql.ErrNoRows` / DB errors to domain sentinel errors; log unexpected errors server-side and return `"internal server error"`. | | Unmarshaling JSON directly into DB structs | Decode into explicit request DTOs with `Validate()`. | | Writing to the same DB tables from both Prisma/Drizzle in Next.js and SQL in Go | Give Go sole ownership of runtime queries; see [COOKBOOK.md §2](COOKBOOK.md#2-database--orm-best-practices-what-about-drizzle-or-prisma). | | Using `app.Router.Use(authMiddleware)` globally | Scope auth middleware to authenticated route groups so public pages, webhooks, `/_nextgin/health`, and static assets stay unaffected. | | Calling `nextgin.ReadJSON` on payment webhooks | Always use `nextgin.ReadRawBody`, verify HMAC in constant time, then `json.Unmarshal`. | | Putting business logic inside Next.js Route Handlers (`app/api/*`) | Put hot API logic in Go; reserve Next.js for UI, SSR, RSC, and thin Server Actions that call Go. | --- # nextgin Cookbook & Best Practices Practical recipes for deploying and hardening apps with Next.js + pure-Go `nextgin`. For application folder layout, separation of concerns (`httpapi → service → store`), handler/error patterns, and the Next.js ↔ Go client boundary, see [docs/PATTERNS.md](PATTERNS.md). --- ## 1. Choosing Your Architecture Pick **one** of these two production layouts: | Pattern | Best For | Hosting | |---|---|---| | **Split (`--web-target vercel --backend-target container`)** | Keeping Next.js on Vercel Hobby/Pro while moving auth, cart, payments, webhooks, and crons off Vercel. | Next.js on Vercel + tiny Go container on Fly.io / Cloud Run / Railway / $5 VPS. | | **Cloudflare (Pages + Containers)** | Running both Next.js and the native Go binary on Cloudflare with zero cold-start Node API bloat. | Next.js on Cloudflare Pages + Go binary on Cloudflare Containers + Cron Triggers. | | **All-in-One VPS (`nextgin deploy`)** | Zero platform limits, zero cross-origin cookie setup, lowest flat monthly cost. | Single $5–10/mo VPS running Go front door + Node workers + Postgres/Redis + Caddy HTTPS. | ### Why Split Defaults to `--api-mode direct` In split mode, `--api-mode direct` sends browser API calls straight to `https://api.yourdomain.com` instead of proxying them through Vercel rewrites: - **Zero Vercel compute/bandwidth** spent on API traffic or webhooks. - **Zero Vercel Cron invocations** (all crons run in Go's in-process scheduler). - **Same-site cookies still work seamlessly** by setting `Domain: ".yourdomain.com"` on `nextgin.CookieOptions` and adding `nextgin.CORS("https://yourdomain.com")`. Use `--api-mode rewrite` only if you cannot put the Go backend on a subdomain of the same root domain. --- ## 2. Database & ORM Best Practices (What About Drizzle or Prisma?) A common question from Next.js developers: *"Should I use Drizzle or Prisma alongside Go?"* ### Short Answer **Do not split runtime writes across two ORMs.** Having Prisma/Drizzle mutate tables in Node while Go writes SQL against the same tables causes schema drift, duplicated validation, and subtle bugs. Pick **one** of these clean patterns: ### Pattern A (Recommended): SQL Migrations + `sqlc` in Go - **Migrations:** Plain SQL files managed by `goose`, `golang-migrate`, or `atlas`. - **Queries:** Write `.sql` queries and generate 100% type-safe Go code with [`sqlc`](https://sqlc.dev/) (zero ORM runtime overhead, full `pgx` or SQLite speed). - **Next.js:** Never connects to the DB directly. Server Components fetch Go over `NEXTGIN_INTERNAL_URL`; client components call Go API endpoints. - **Why it wins:** One DB connection pool (in Go), one schema owner, ~15–20× higher API throughput than Node route handlers, and no Prisma binary bloat in Next.js bundles. ### Pattern B (Pragmatic for TypeScript Teams): Drizzle/Prisma as *Schema & Migration Tool Only* If your team already loves Drizzle Kit (`drizzle-kit generate` / `drizzle-kit migrate` / Drizzle Studio) or Prisma Migrate: 1. Keep your schema definition in `web/db/schema.ts` (Drizzle) or `prisma/schema.prisma`. 2. Run migrations with Drizzle/Prisma in CI/deploy. 3. Let **Go own runtime API reads/writes** (using `sqlc` pointed at the generated SQL migrations, or `pgx`/`database/sql`). 4. Do **not** import the TS ORM in hot API paths. ### Pattern C (Domain Split — Only When Needed) If you have read-heavy CMS/editorial pages in Next.js Server Components that you want to query with Drizzle directly, draw a **hard table boundary**: - **Go owns:** `users`, `sessions`, `carts`, `orders`, `payments`, `cron_runs` (transactional, rate-limited, webhook-driven). - **Next.js (read-only) reads:** `pages`, `posts`, `catalog` (or just calls Go over loopback `NEXTGIN_INTERNAL_URL`, which is usually simpler and avoids maintaining two DB pools). --- ## 3. Auth, Sessions & Rate Limiting Always rate-limit `/login` and `/register`, and set `HttpOnly` + `Secure` + `SameSite=Lax` cookies via `nextgin.SetSessionCookie`: ```go cookieOpts := nextgin.CookieOptions{ Domain: ".example.com", // omit on single-host selfhost MaxAge: 7 * 86400, Insecure: os.Getenv("COOKIE_INSECURE") == "1", // true ONLY on http://localhost } authLimit := nextgin.RateLimitWithConfig(nextgin.RateLimitConfig{ RPS: 2, Burst: 10, TrustForwardedHeaders: true, // only behind Caddy / Fly / Cloud Run / Cloudflare }) api.POST("/auth/login", func(w http.ResponseWriter, r *http.Request) { var body struct { Email string `json:"email"` Password string `json:"password"` } if err := nextgin.ReadJSON(r, &body); err != nil { if errors.Is(err, nextgin.ErrBodyTooLarge) { nextgin.WriteError(w, http.StatusRequestEntityTooLarge, "body too large") return } nextgin.WriteError(w, http.StatusBadRequest, "invalid json") return } // Verify password (bcrypt/argon2), create session row in DB... nextgin.SetSessionCookie(w, "sid", sessionToken, cookieOpts) nextgin.WriteJSON(w, http.StatusOK, map[string]bool{"ok": true}) }, authLimit) api.POST("/auth/logout", func(w http.ResponseWriter, r *http.Request) { // Delete session row in DB... nextgin.ClearSessionCookie(w, "sid", cookieOpts) w.WriteHeader(http.StatusNoContent) }) ``` --- ## 4. Payment Webhooks (Stripe / Paystack / LemonSqueezy) **Rule:** Never parse a webhook with `ReadJSON` before verifying its signature. Always read the exact raw bytes with `nextgin.ReadRawBody`, verify the HMAC in constant time, and make the handler **idempotent** (payment providers retry webhooks): ```go api.POST("/webhooks/pay", func(w http.ResponseWriter, r *http.Request) { raw, err := nextgin.ReadRawBody(w, r, 256<<10) // 256 KiB cap if err != nil { nextgin.WriteError(w, http.StatusBadRequest, "invalid body") return } mac := hmac.New(sha256.New, []byte(os.Getenv("PAYMENT_WEBHOOK_SECRET"))) mac.Write(raw) expected := hex.EncodeToString(mac.Sum(nil)) if !hmac.Equal([]byte(r.Header.Get("X-Pay-Signature")), []byte(expected)) { nextgin.WriteError(w, http.StatusUnauthorized, "invalid signature") return } var evt struct { EventID string `json:"id"` OrderID string `json:"orderId"` } if err := json.Unmarshal(raw, &evt); err != nil { nextgin.WriteError(w, http.StatusBadRequest, "malformed event") return } // Idempotent update: UPDATE orders SET status='paid' WHERE id=$1 AND status='pending' w.WriteHeader(http.StatusOK) }) ``` --- ## 5. Reliable Cron Jobs & Rolling-Deploy Locking Crons run in-process on `selfhost` and `backend` targets — no Vercel Hobby daily limit and no per-invocation billing. ### Always Respect `r.Context()` On `SIGTERM`, `nextgin` cancels the request context passed to every running cron job and waits up to `Config.ShutdownGrace` (default 10s): ```go app.Cron("expire-carts", "*/5 * * * *", func(w http.ResponseWriter, r *http.Request) { if _, err := db.ExecContext(r.Context(), `DELETE FROM cart_items WHERE updated_at < NOW() - INTERVAL '15 minutes'`); err != nil { nextgin.WriteError(w, http.StatusInternalServerError, err.Error()) return } w.WriteHeader(http.StatusNoContent) }) ``` ### Preventing Double-Runs During Rolling Deploys (`CronLocker`) During a zero-downtime deploy, old and new containers overlap for 10–30 seconds. Implement `nextgin.CronLocker` with a Postgres advisory lock (or Redis `SET NX PX`) so only one container runs a job at a time: ```go type pgCronLocker struct{ db *sql.DB } func (l pgCronLocker) TryLock(ctx context.Context, jobName string, _ time.Duration) (func(), bool, error) { conn, err := l.db.Conn(ctx) if err != nil { return nil, false, err } key := int64(fnvHash64("nextgin:cron:" + jobName)) var acquired bool if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, key).Scan(&acquired); err != nil { conn.Close() return nil, false, err } if !acquired { conn.Close() return nil, false, nil } return func() { _, _ = conn.ExecContext(context.Background(), `SELECT pg_advisory_unlock($1)`, key) conn.Close() }, true, nil } ``` Pass it into `nextgin.Config{CronLocker: pgCronLocker{db: db}}`. --- ## 6. Server-to-Server Calls (Next.js SSR / Server Actions → Go) When Next.js Server Components or Server Actions need private data from Go: 1. Protect the Go route group with `nextgin.RequireInternal()`: ```go internal := app.Router.Group("/internal", nextgin.RequireInternal()) internal.GET("/orders/{id}", handleGetOrder) ``` 2. Set the same `NEXTGIN_INTERNAL_SECRET` on both Next.js and Go. 3. Call Go from Next.js using `NEXTGIN_INTERNAL_URL`: ```ts const res = await fetch(`${process.env.NEXTGIN_INTERNAL_URL}/internal/orders/${id}`, { headers: { 'X-Nextgin-Internal': process.env.NEXTGIN_INTERNAL_SECRET! }, cache: 'no-store', }) ``` --- ## 7. Deploying on Cloudflare (Pages + Containers) Because `NEXTGIN_TARGET=backend` runs your pure-Go API and cron routes as a standalone ~7.5 MB HTTP server (with `app.MountFrontend()` as a no-op), it fits cleanly inside a `lite` (256 MiB) **Cloudflare Container** while your Next.js frontend lives on **Cloudflare Pages**. ### 1. Build the Linux/AMD64 Go Binary ```bash CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o cf-backend/bin/server . ``` ### 2. Minimal Container `Dockerfile` (`cf-backend/Dockerfile`) ```dockerfile FROM alpine:3.21 RUN apk add --no-cache ca-certificates WORKDIR /app COPY bin/server /app/server RUN chmod +x /app/server ENV NEXTGIN_TARGET=backend \ PORT=8080 \ TRUST_PROXY=1 EXPOSE 8080 CMD ["/app/server"] ``` ### 3. Wrangler Config (`cf-backend/wrangler.jsonc`) ```jsonc { "name": "my-app-api", "main": "src/index.ts", "compatibility_date": "2026-03-01", "compatibility_flags": ["nodejs_compat"], "containers": [ { "class_name": "NextginGoBackend", "image": "./Dockerfile", "instance_type": "lite", "max_instances": 2 } ], "durable_objects": { "bindings": [ { "name": "NEXTGIN_GO", "class_name": "NextginGoBackend" } ] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["NextginGoBackend"] } ], "routes": [ { "pattern": "api.example.com", "custom_domain": true } ], "triggers": { "crons": ["*/15 * * * *"] } } ``` ### 4. Worker Entry + Cron Trigger (`cf-backend/src/index.ts`) Cloudflare Containers can sleep after idle periods (`sleepAfter`). Forwarding Worker Cron Triggers to `nextgin`'s authenticated `/_nextgin/cron/` route guarantees your jobs run even when the container is asleep: ```ts import { Container, getContainer } from '@cloudflare/containers' interface Env { NEXTGIN_GO: DurableObjectNamespace CRON_SECRET?: string } export class NextginGoBackend extends Container { defaultPort = 8080 sleepAfter = '15m' constructor(ctx: DurableObjectState, env: Env) { super(ctx, env) this.envVars = { NEXTGIN_TARGET: 'backend', PORT: '8080', TRUST_PROXY: '1', ...(env.CRON_SECRET ? { CRON_SECRET: env.CRON_SECRET } : {}), } } } export default { async fetch(request: Request, env: Env): Promise { return getContainer(env.NEXTGIN_GO, 'primary').fetch(request) }, async scheduled(_event: ScheduledEvent, env: Env): Promise { const headers: Record = {} if (env.CRON_SECRET) { headers['Authorization'] = `Bearer ${env.CRON_SECRET}` } await getContainer(env.NEXTGIN_GO, 'primary').fetch( new Request('http://container/_nextgin/cron/expire-carts', { method: 'POST', headers, }), ) }, } ``` Deploy the Go container backend: ```bash cd cf-backend npx wrangler secret put CRON_SECRET # optional, matches CRON_SECRET in Go npx wrangler deploy ``` ### 5. Connect the Next.js Frontend on Cloudflare Pages You have two options for routing `/api/*` from Cloudflare Pages to your Go container: - **Direct subdomain (recommended for high traffic):** Point `NEXT_PUBLIC_NEXTGIN_API_URL=https://api.example.com`, add `nextgin.CORS("https://example.com")`, and set `Domain: ".example.com"` on session cookies. - **Same-origin Pages Function proxy:** Add `functions/api/[[path]].js` in your Pages project and set `NEXTGIN_BACKEND_URL=https://api.example.com` in Cloudflare Pages environment variables: ```js // functions/api/[[path]].js export async function onRequest(context) { const backend = context.env.NEXTGIN_BACKEND_URL if (!backend) { return new Response(JSON.stringify({ error: 'NEXTGIN_BACKEND_URL not set' }), { status: 502, headers: { 'content-type': 'application/json' }, }) } const incoming = new URL(context.request.url) const target = new URL(incoming.pathname + incoming.search, backend) return fetch(new Request(target.toString(), context.request)) } ``` > **Note:** Cloudflare Containers requires the Cloudflare Workers Paid plan. --- ## 8. Production Checklist - [ ] **Reverse proxy:** Set `Config.TrustForwardedHeaders: true` when behind Caddy, Nginx, Cloudflare, Fly.io, or Cloud Run (leave `false` if exposed directly to the internet). - [ ] **Healthcheck:** Point Docker / Fly.io / Cloud Run / Load Balancer probes at `GET /_nextgin/health`. - [ ] **Cookies:** Leave `CookieOptions.Insecure: false` in production (HTTPS). - [ ] **Secrets:** Set `CRON_SECRET` (if triggering crons externally) and `NEXTGIN_INTERNAL_SECRET` (for `/internal/*` routes). - [ ] **SQLite (if used):** Enable WAL mode + `busy_timeout(5000)` + `foreign_keys(ON)` and mount a persistent volume (single-instance deploys only; use Postgres for multi-instance). - [ ] **Backups:** Set up automated Postgres/SQLite backups (not handled by `nextgin deploy`). --- # Deployment Guide `nextgin` supports two primary production topologies using the exact same Go backend and Next.js App Router codebase. ## 1. All-in-One Self-Host (Render, Fly.io, Railway, VPS) In `selfhost` mode, Go is the single public HTTP front door: - Static assets (`/_next/static/*`, `/public/*`) and prerendered HTML are served directly by Go. - `/api/*` and `/_nextgin/cron/*` are handled in-process by Go `net/http`. - Dynamic SSR, RSC, and Server Actions are proxied to Next.js standalone workers over Unix domain sockets with `WriteTimeout: 0` so Suspense streaming never cuts off. ### Sizing for Render 512 MB (Free / Starter) A stripped pure-Go binary (`CGO_ENABLED=0 -ldflags="-s -w"`) is ~8 MB and idles at ~10–15 MB RAM. Setting `WORKERS=1` keeps total container memory around 100–140 MB — well inside a 512 MB instance. ```dockerfile FROM golang:1.24-alpine AS go-builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server . FROM node:22-alpine AS runner WORKDIR /app ENV NODE_ENV=production WORKERS=1 TRUST_PROXY=1 PORT=8080 COPY --from=go-builder /app/server ./server COPY .nextgin ./.nextgin HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://127.0.0.1:8080/_nextgin/health || exit 1 EXPOSE 8080 CMD ["./server"] ``` ### Health Checks & Zero-Downtime Rolling Deploys Point your platform's health check at `GET /_nextgin/health`. On `SIGTERM`, Go stops accepting new connections, cancels cron contexts (`r.Context()`), drains active HTTP requests, and shuts down Next.js workers cleanly. --- ## 2. Split Mode: Vercel (or Cloudflare Pages) + Go Container Keep your Next.js frontend on **Vercel** (or **Cloudflare Pages**) while your Go API, webhooks, and unlimited crons run on **Render, Fly.io, Cloud Run, or Railway**. ```bash nextgin build \ --web-target vercel \ --backend-target container \ --backend-url https://api.example.com ``` ### Why Direct Browser → Go API Mode? By default in split mode, browser requests go directly to `https://api.example.com` instead of proxying through Vercel rewrites: - **Zero Vercel API compute charges** and no 10s–60s serverless timeout on long jobs. - **Parent-domain cookies**: configure `SetSessionCookie` with `Domain: ".example.com"` and `CORS` with explicit `https://example.com` origin. - **No `api/` directory at project root**: keep `web/` and `backend/` separate so Vercel never mistakes Go files for legacy serverless functions. ### Note on Cloudflare Workers / WASM We intentionally do **not** compile the Go backend to Cloudflare Workers WASM. Native Go containers give you persistent PostgreSQL/SQLite connection pools, Unix sockets, full stdlib networking, and reliable in-process cron goroutines without WASM isolate limits. You can still host the Next.js frontend on Cloudflare Pages and point `NEXT_PUBLIC_NEXTGIN_API_URL` at your Go container. --- # Security & In-Process Crons Every security boundary in `nextgin` is designed to **fail closed** so misconfiguration never silently opens an endpoint. ## Fail-Closed HTTP Primitives ### Strict JSON Parsing (`ReadJSON`) `nextgin.ReadJSON(w, r, &dto)` enforces `DefaultMaxBodyBytes` (1 MiB), rejects unknown or malformed JSON, and rejects trailing tokens after the first JSON value. ```go var req CreateOrderRequest if err := nextgin.ReadJSON(w, r, &req); err != nil { nextgin.WriteError(w, http.StatusBadRequest, err.Error()) return } ``` ### Exact-Byte Payment Webhooks (`ReadRawBody`) Never decode Stripe, Paystack, or GitHub webhook bodies with `ReadJSON` before verifying signatures. Use `ReadRawBody` to read exact wire bytes with a strict byte cap: ```go raw, err := nextgin.ReadRawBody(w, r, 256<<10) // 256 KiB cap if err != nil { nextgin.WriteError(w, http.StatusBadRequest, "invalid body") return } // Verify HMAC-SHA256 using crypto/hmac.Equal before json.Unmarshal ``` ### Strict CORS & Proxy Trust - `nextgin.CORS(nextgin.CORSConfig{AllowedOrigins: []string{"https://app.example.com"}})` **panics at startup** if `AllowedOrigins` is empty or contains `"*"`. - `X-Forwarded-For` and `X-Forwarded-Proto` are **ignored** unless `TrustForwardedHeaders: true` is explicitly configured behind a trusted reverse proxy. ### Per-IP Rate Limiting (`RateLimit`) Built-in token-bucket limiter with automatic idle eviction and `429 Too Many Requests` + `Retry-After` headers: ```go auth := api.Group("/auth") auth.Use(nextgin.RateLimit(5, 10)) // 5 req/sec, burst 10 ``` ### Internal SSR Auth (`RequireInternal`) Protect Go endpoints meant only for Next.js Server Components / Server Actions: ```go internal := api.Group("/internal") internal.Use(nextgin.RequireInternal()) ``` If `NEXTGIN_INTERNAL_SECRET` is unset, `RequireInternal()` returns `401 Unauthorized` for every request. --- ## Reliable In-Process Crons Every cron job in `nextgin` is an authenticated HTTP route registered under `/_nextgin/cron/`: ```go app.Cron("expire-carts", "* * * * *", func(w http.ResponseWriter, r *http.Request) { if err := r.Context().Err(); err != nil { nextgin.WriteError(w, http.StatusServiceUnavailable, "shutting down") return } if err := cartService.ExpireStale(r.Context()); err != nil { nextgin.WriteError(w, http.StatusInternalServerError, err.Error()) return } w.WriteHeader(http.StatusNoContent) }) ``` ### Key Guarantees 1. **Fail-closed auth**: Only the per-process internal bearer token or `CRON_SECRET` can invoke `/_nextgin/cron/*`. 2. **Excluded from public exports**: `/_nextgin/*` routes are never exported to public Vercel rewrite tables. 3. **Graceful shutdown**: Always pass `r.Context()` to DB queries and HTTP calls so `SIGTERM` cancels long jobs cleanly. 4. **Multi-replica safety**: Attach a `CronLocker` (PostgreSQL advisory lock or Redis `SET NX`) in `nextgin.Config` so rolling deploys never double-run a tick. --- # CLI Reference `@nextgin/adapter` ships the `nextgin` CLI for scaffolding, local development, multi-target builds, and single-VPS deployments. ## `nextgin init` Scaffolds a production-ready Next.js App Router + pure-Go 3-layer application (`internal/{domain,store,service,httpapi}`) with `httptest` tests, typed `lib/api.ts`, and a project `AGENTS.md`. ```bash npx @nextgin/adapter init my-app npx @nextgin/adapter init my-app --layout split --module github.com/acme/my-app ``` | Flag | Default | Description | |---|---|---| | `[dir]` | `.` | Target directory to scaffold into | | `--layout` | `selfhost` | `selfhost` (single repo) or `split` (`web/` + `backend/` directories) | | `--name` | directory name | Package name written to `package.json` | | `--module` | `example.com/` | Go module path written to `go.mod` | | `--force` | `false` | Allow scaffolding into a non-empty directory | ## `nextgin dev` Starts the Next.js development server (Turbopack HMR) and runs `go run .` in dev proxy mode so all `/api/*` and `/_nextgin/cron/*` routes are handled by Go while frontend edits hot-reload immediately. ```bash npx nextgin dev ``` | Environment Variable | Default | Description | |---|---|---| | `PORT` | `8080` | Public Go front-door listen port | | `NEXT_PORT` | `3001` | Internal Next.js dev server port | | `NEXTGIN_INTERNAL_SECRET` | unset | Shared secret for SSR → Go loopback calls | ## `nextgin build` Runs `next build`, emits `.nextgin/manifest.json` (static files, prerendered HTML routes, worker routes), copies the standalone Next.js server, and compiles the Go binary — or generates split-target artifacts (`web/vercel.json`, `backend/Dockerfile`). ```bash # Self-hosted single binary + standalone worker nextgin build # Split mode: Next.js on Vercel + pure-Go container backend nextgin build \ --web-target vercel \ --backend-target container \ --backend-url https://api.example.com ``` | Flag | Default | Description | |---|---|---| | `--web-target` | `selfhost` | `selfhost` or `vercel` | | `--backend-target` | `selfhost` | `selfhost` or `container` | | `--backend-url` | — | Public HTTPS origin of the Go backend in split mode | ## `nextgin deploy` Builds and deploys a self-hosted `nextgin` app to any SSH-accessible Linux VPS with Docker, automatic Caddy HTTPS, optional PostgreSQL, and optional Redis. ```bash nextgin deploy \ --host root@203.0.113.7 \ --domain app.example.com \ --postgres \ --redis ``` | Flag | Description | |---|---| | `--host` | SSH target (`user@ip-or-hostname`) | | `--domain` | Public domain for automatic Caddy TLS certificates | | `--postgres` | Provision a managed PostgreSQL container + `DATABASE_URL` | | `--redis` | Provision a Redis container + `REDIS_URL` for `CronLocker` | | `--env-file` | Local `.env` file synced securely to the server | --- # nextgin multi-target spec Status: authoritative for all work on the `multi-target` branch. Dispatch instructions cite sections of this file by number (e.g. "SPEC §3.2"). ## 1. Goal One codebase — a Next.js frontend plus a Gin backend with API routes and scheduled jobs — deploys to three targets: | Target | HTTP front door | Next.js | Gin backend | Cron trigger | |---|---|---|---|---| | `selfhost` (done, v0) | Go | UDS worker pool behind Go | same process | in-process scheduler (§3.4) | | `vercel` | Vercel router | Vercel's native Next.js | Vercel Service, `framework: go`, native | `vercel.json` `crons` → cron route | | `cloudflare` | Next Worker (OpenNext) | OpenNext Cloudflare | separate Worker, Go→wasm, persistent instance (§5) | Worker Cron Trigger → cron route in-process | Split topologies (web and backend on different hosts) are specified in §9. Design rule: **a cron job is a Gin route.** Every target executes a job by sending a request through the same Gin engine and middleware chain as API traffic. Targets differ only in what triggers that request. ## 2. Build split (hard invariant) - Files that use the worker pool, `os/exec`, Unix sockets or process signals carry `//go:build !js`. Today: `worker_pool.go`, `sysprocattr_*.go`, and the Frontend/selfhost parts of `nextgin.go` (to be moved into `selfhost.go`, `//go:build !js`). - Portable files (no build tag): `manifest.go`, `handler.go`, `cron.go`, `cron_route.go`, `export.go`, `target.go`. - Cloudflare runtime: `cloudflare_js.go` with `//go:build js && wasm`. - `GOOS=js GOARCH=wasm go build ./...` MUST succeed. It is part of the verification gate (§8). ## 3. Cron jobs (portable core) ### 3.1 Canonical schedule syntax Exactly 5 space-separated fields, UTC, Vercel-compatible numeric subset: | Field | Range | |---|---| | minute | 0–59 | | hour | 0–23 | | day of month | 1–31 | | month | 1–12 | | day of week | 0–6 (0 = Sunday) | Each field is a comma-separated list of items. Allowed item forms: `*`, `N`, `N-M`, `*/S`, `N-M/S`. N, M and S are decimal integers. `S >= 1`. `N <= M`. All values within the field's range. Rejected (error at parse time): names (`MON`, `JAN`), `?`, `L`, `W`, `#`, `@hourly`-style macros, 6-field (seconds) expressions, empty items, and any expression where **both** day-of-month and day-of-week are not `*` (Vercel restriction; keeps semantics identical on every platform). ### 3.2 `cron.go` API (portable) ```go // Schedule is a parsed canonical cron expression. type Schedule struct { /* unexported: sets of allowed values per field */ } func ParseSchedule(expr string) (*Schedule, error) func (s *Schedule) String() string // canonical input, whitespace-normalized func (s *Schedule) Next(after time.Time) time.Time // first matching minute strictly after `after`, UTC, seconds=0 func (s *Schedule) RunsPerDayMax() int // len(minutes) * len(hours); >1 means sub-daily func (s *Schedule) CloudflareExpr() string // §3.3 ``` `Next` must terminate for every valid schedule (e.g. `0 0 31 2 *` never matches: return the zero `time.Time` after scanning at most 5 years). ### 3.3 Cloudflare translation Cloudflare day-of-week is 1–7 with 1 = Sunday. `CloudflareExpr()` returns the canonical expression with only the day-of-week field rewritten: `*` stays `*`; anything else is expanded to the explicit sorted list of canonical values, each +1, comma-joined (e.g. `1-5` → `2,3,4,5,6`, `*/2` → `1,3,5,7`). Other fields are emitted unchanged. ### 3.4 Registration and routes (`cron_route.go`) ```go func (a *App) Cron(name, schedule string, handlers ...gin.HandlerFunc) ``` - `name` must match `^[a-z0-9][a-z0-9_-]{0,62}$` and be unique; schedule must parse. Violations **panic** at registration (same as Gin route conflicts) with a message naming the job. - Registers `GET` and `POST` on `/_nextgin/cron/` with `cronAuth` middleware first, then the user's handlers. - `cronAuth` (fail closed): accept iff the `Authorization` header equals `Bearer ` (constant-time compare) where token is either the process-internal token (32 random bytes, hex, generated once per process) or the value of env `CRON_SECRET` when that is non-empty. Otherwise `401` with JSON `{"error":"unauthorized"}` and abort. - The App keeps an ordered registry of jobs: `{Name, Schedule, Path}`. ### 3.5 Self-host scheduler Started by `App.Run` on the selfhost target only (never on vercel/cloudflare, never in export mode). One goroutine per job: - Sleep until `Schedule.Next(now)`; then invoke the job by calling `a.Router.ServeHTTP` in-process with a synthetic `POST` request to the job path, header `Authorization: Bearer `, header `X-Nextgin-Cron: `, and a context with timeout `Config.CronTimeout` (default 5 minutes). - Overlap guard: if the previous run of the same job is still executing when the next fire time arrives, skip that run and log a warning. - Log each run at Info with name, status code and duration; status >= 400 logs at Error. - Stops when Run's context is cancelled (graceful shutdown waits for in-flight job runs up to `ShutdownGrace`). ## 4. Targets and export ### 4.1 Target detection (`target.go`) `Target()` returns, in order: env `NEXTGIN_TARGET` if set (`selfhost`, `vercel`, `cloudflare`; anything else → error at `New`); else `vercel` if env `VERCEL == "1"`; else `cloudflare` when built for `js/wasm`; else `selfhost`. Behavior of `New`/`Run` per target: - `selfhost`: unchanged v0 behavior (workers, frontend) + scheduler (§3.5). - `vercel`: no manifest, no workers, no frontend, no scheduler. `Run` listens on `:$PORT` (default `3000`) serving `a.Router` only. - `cloudflare`: §5. - **Export mode** (env `NEXTGIN_EXPORT=1`, any target): `New` must not read the manifest, start workers or touch disk. `Run` writes the export JSON (§4.2) to the file named by `NEXTGIN_EXPORT_FILE` (stdout when unset) and exits with status 0. The CLI always sets the file: gin prints debug output to stdout before `nextgin.New` runs when the user builds the router themselves, so stdout cannot be trusted to carry only JSON. ### 4.2 Export JSON (`export.go`) ```json { "version": 1, "routes": [{"method": "GET", "path": "/api/todos"}], "crons": [{"name": "cleanup", "schedule": "*/5 * * * *", "cloudflare": "*/5 * * * *", "path": "/_nextgin/cron/cleanup", "runsPerDayMax": 288}] } ``` `routes` comes from `gin.Engine.Routes()`, excluding `/_nextgin/` paths, sorted by path then method. The CLI derives platform config from this file; Go code is the single source of truth. ## 5. Cloudflare runtime (option 1: wasm, persistent instance) Measured (local `wrangler dev`, p50): workers-go default glue boots a new Go runtime per request (44.6 ms trivial endpoint vs 12.6 ms plain JS); keeping one instance alive gives 13.8 ms. Therefore: - Go side (`cloudflare_js.go`): `workers.ServeNonBlock(a.Router)`; `cron.ScheduleTaskNonBlock(task)` where `task` reads `cron.NewEvent(ctx)`, looks up every job whose `CloudflareExpr()` equals `event.Cron`, and invokes each in-process exactly as §3.5 does (internal token); then `workers.Ready()` and block forever (`select {}`). - JS side: the CLI patches the workers-go generated `build/worker.mjs` so `fetch` and `scheduled` share one lazily created instance (one `run()` promise) instead of calling `run()` per event. - Failure handling (verified under `wrangler dev`): - workers-go v0.36.0 panics when the scheduled task returns an error, which would kill the persistent instance. The task therefore always returns nil; an unmatched expression or a job answering >= 400 is recorded on `globalThis.__nextginCronErrors[event.cron]` and the glue's `scheduled()` throws it, so Cloudflare reports the invocation as failed while the Go instance keeps serving. - If the Go program exits (unrecovered panic in a goroutine), the glue sees `go.exited` on the next event and boots a fresh instance. Exit cannot be observed through `go.run()`'s promise: workerd does not run continuations of a promise resolved from a different request context. - In-memory Go state does not survive a reboot or isolate eviction; keep durable state in a binding (KV/D1/R2) or an external store. - Known v1 limitation (document, do not work around): the runtime context (env/ctx) is captured from the first event; `waitUntil` of later events is not wired. - Requires the Workers Paid plan in practice (free plan CPU limit 10 ms). - Measured (local `wrangler dev`, warm, p50 of 60): persistent glue with `gin.Default()` 12.2 ms, with a logger-free `gin.New()` 8.6 ms — gin's per-request logger writes through console.log. The stock workers-go glue cannot serve this runtime at all (the Go side blocks forever by design). - Limits that apply (developers.cloudflare.com/workers/platform/limits): 64 MiB uncompressed Worker size, no compressed limit; 128 MB memory per isolate; 1 s global-scope startup. See wasm size below. - Wasm size (measured on the example): 41.9 MB default; 28.4 MB with -tags nomsgpack; 10.0 MB with nomsgpack, -trimpath -ldflags=-s -w and no gin binding (nextgin.BindJSON). The CLI builds with -tags nomsgpack (override: --go-tags) and warns above 20 MiB. wasm-opt -Oz was measured at a further 8% for 148 s of build time and is not used. Per-isolate cost (V8 WebAssembly.compile in Node, median of 5): 107 ms -> 33 ms; whole-process CPU 304 ms -> 122 ms. Production CPU after the change is not yet measured. ## 6. CLI targets (`nextgin build --target ...`) Project layout for multi-target apps: a root with `web/` (Next.js) and `backend/` (Go module with `main.go`). Never name a directory `api/` (Vercel treats it as legacy functions). - `vercel`: run export; write root `vercel.json` (Vercel Services, beta; schema verified against vercel.com/docs/services, /routing, /bindings): - `services.web = {"root": "web/", "framework": "nextjs", "bindings": [{"type": "service", "service": "backend", "format": "url", "env": "NEXTGIN_INTERNAL_URL"}]}` — bindings are declared by the caller; Go services cannot declare bindings, but Next calling Go is the direction we need. - `services.backend = {"root": "backend/", "framework": "go"}` — the `go` slug is not in the docs but is in the CLI's framework table (detectors: go.mod + main.go). It is required: with `root` only, `vercel dev` did not detect the service and the rewrite answered 502 "Cannot route to service `backend`: it is not running". - `rewrites`, in order: `//:path*` → `{"service": "backend"}` for each distinct static first path segment of exported routes; then `/_nextgin/:path*` → backend; then `/(.*)` → `{"service": "web"}`. Services receive the original path; routing into a service is final (no fall-through), so a prefix belongs wholly to Go. - `crons`: `{"path", "schedule"}` per exported job. `--check` fails if the committed file differs. `--vercel-hobby` fails the build when any job has `runsPerDayMax > 1`. - `cloudflare`: OpenNext build of `web/`; `GOOS=js GOARCH=wasm` build of `backend/` + glue patch (§5); generated wrangler configs with the backend service binding and Cron Triggers from `cloudflare` expressions. - The Next adapter is a no-op (returns `undefined`) unless the target is `selfhost`. Vercel builds set `VERCEL=1`; the CLI passes `NEXTGIN_TARGET=cloudflare` to the OpenNext build. Anyone running `opennextjs-cloudflare build` directly must set it too. - The web worker forwards only the exported Go prefixes to the backend; `/_nextgin/*` is not publicly routed on Cloudflare (Cron Triggers reach the backend worker directly). Verified locally (2026-11-16): Cloudflare web + backend workers together under `wrangler dev` (multi-config) with OpenNext 1.20.17 — Go API via the service binding, prerendered pages, SSR fetching `NEXTGIN_INTERNAL_URL`, proxy.ts, next.config headers/redirects, Suspense streaming, Server Actions persisting through Go, Cron Triggers running Go jobs in-process. Verified locally (2026-11-16, `vercel dev`, CLI 65.16.0, linked scratch project): the generated services config is accepted; both services run; Go prefixes and `/_nextgin/*` route to Go, everything else to Next (404s from Next); the binding injects `NEXTGIN_INTERNAL_URL` (SSR and Server Actions reach Go); proxy.ts and next.config headers run; the Go process sees `VERCEL=1` (vercel target, no scheduler); a cron-shaped request (GET + `Authorization: Bearer $CRON_SECRET`) through the router runs the job, a wrong secret is 401. Deploy-tested (2026-11-16, scratch app = the example, both targets, then torn down): - Vercel (Hobby, `vercel deploy --prod`): the remote Go build fetched the private `github.com/Chidi09/nextgin` with `GIT_CREDENTIALS` passed as a build-only env (`--build-env`), plus `GOPRIVATE`. Production URL: Go API, SSR + Server Action via the binding, proxy.ts, headers, cron route 401 without / 204 with `CRON_SECRET`. First request 6.0 s (cold); warm Go API p50 ~90 ms above a static asset from the same client. Hobby rejects the deploy outright for any sub-daily cron (`--vercel-hobby` catches it first). - Cloudflare (Workers Paid): `wrangler deploy` backend then web. Upload 42.9 MB (8.8 MB gzip), reported startup 3 ms (Go boots on first event). Everything above works through the web worker. Production `event.cron` arrived as exactly `* * * * *` and ran the job in-process (204) — the CloudflareExpr matching assumption holds. Analytics over 79 invocations: CPU p50 3.3 ms, p90 279 ms, p99 552 ms; wall p50 14.6 ms, p99 1.66 s. The tail is Go booting: at low traffic requests spread across many isolates and ~1 in 4 booted a fresh instance (first request 7.0 s). Server Action write and read-back landed in different isolates, so in-memory state is per isolate (expected; see §5). Open items: - (Closed) Vercel's production cron invoker reaches a service path: the daily heartbeat fired at 23:46:10 UTC (within its 23:00 hour on Hobby) as GET /_nextgin/cron/heartbeat on service `backend`, Bearer CRON_SECRET accepted, 204. Resolved after the first deploy (re-deployed and verified 2026-11-16): - The generated backend wrangler.jsonc sets `workers_dev: false` and `preview_urls: false`. Its workers.dev URL returns 404; the web worker's binding (API, SSR via `NEXTGIN_INTERNAL_URL`) and Cron Triggers still work. Note: the first trigger fired ~5 min after the redeploy. - vercel/cloudflare targets switch Gin to release mode unless `GIN_MODE` is set; production boot logs no longer show `[GIN-debug]` output. Also: a Vercel Go build must be able to fetch `github.com/Chidi09/nextgin` (public repo, or GOPRIVATE + token); production Cloudflare `event.cron` matching `CloudflareExpr()` byte for byte (a mismatch now fails loudly); real cold start and CPU cost of the ~43 MB example wasm. ## 7. Known bug to fix first `worker_pool.go` marks a worker not-ready on any dial error, and only the READY line sets it back. A live worker that refuses one connection (full listen backlog under load) leaves rotation permanently. Required fix: on a dial failure, mark not-ready and start a background re-probe for that worker (dial its socket every 100 ms, up to 5 s); on success mark ready again; if the probe times out while the process is still running, kill the process so the supervisor restarts it. ## 8. Verification gate (run after every dispatch, by the reviewer) ```bash gofmt -l . # must print nothing go vet ./... go test -race -count=1 ./... GOOS=js GOARCH=wasm go build ./... # from §2 onward (cd packages/adapter && npx tsc -p tsconfig.json && node --test test/) npm run build -w fullstack-app && scripts/e2e.sh node && scripts/e2e.sh bun ``` ## 9. Split topology (web target x backend target) Status: Go side (§9.2, §9.3 CORS, §9.5) and CLI (§9.1, §9.4, §9.6) implemented and verified locally; not yet deployed to real Vercel/Cloudflare; §9.7 spiked locally (works, with limits). The combined targets (§1) run the Go backend inside the same platform as Next.js, so Go work is still metered by that platform (on Vercel a cron or webhook is a billed function invocation with a duration cap and no persistent state). The split topology puts Next.js and the Go backend on independent hosts so backend work, crons, DB pooling and webhooks leave the web platform. Rendering (SSR, Server Actions) stays on the web platform; this does not reduce that bill. Backend hosting is a choice, not a requirement. Users whose data lives in managed Postgres/Redis do not want to run a server, so the first-class no-server backend is Cloudflare Workers (existing §5 build); a persistent host is the second option. ### 9.1 CLI `nextgin build --web-target vercel --backend-target --backend-url [--api-mode rewrite|direct]`. (`--web` and `--backend` already name the project directories, so the target flags are `--web-target` and `--backend-target`.) `--target` stays the combined in-platform mode, unchanged, and cannot be mixed with the split flags. Phase 1 supports `--web-target vercel` only; web=cloudflare with backend=container waits for Cloudflare Containers (option 2). Split `vercel.json` is written to `/vercel.json` (the Vercel project Root Directory is the web dir; Services are not used because only the web app deploys to Vercel). `rewrite` mode: `rewrites` with external destinations `//:path*`. `direct` mode: `{}`. `/_nextgin/*` is never proxied. ### 9.2 API-only backend mode (`container`) New target `backend` (`NEXTGIN_TARGET=backend`): no manifest, no frontend, no workers; `New(dir, cfg)` must succeed with a missing `dir`. Runs the in-process scheduler (§3.5), listens on `:$PORT`, applies Gin release mode. `MountFrontend` is a no-op. `nextgin build --backend-target container` emits `/Dockerfile` (multi-stage Go build, `ENV NEXTGIN_TARGET=backend`) and does not pick a host. Single instance by default; `NEXTGIN_SCHEDULER=off` disables the scheduler on replicas (leader election is out of scope). ### 9.3 Browser routing (`--api-mode`, default `rewrite`) - `rewrite`: `vercel.json` has `rewrites` `//:path*` -> `//:path*` for each exported Go prefix, no `services.backend`, no `crons`. Same-origin, no client changes. Verify how Vercel bills external rewrites from vercel.com/docs before the README claims any saving. - `direct`: no rewrites. Browser calls `` itself. Requires Go middleware `nextgin.CORS(origins ...string)` (explicit allow-list, credentials on, never `*` with credentials) and documented cookie guidance (`Domain=` on the shared parent, `SameSite`, `Secure`). The CLI prints `NEXT_PUBLIC_NEXTGIN_API_URL=` for client code. ### 9.4 Crons Split builds emit no `crons` in `vercel.json`. `container` runs the scheduler; `cloudflare` uses Cron Triggers (§3.3). Vercel does zero invocations for jobs. ### 9.5 Server-to-server auth (fail closed) The backend is public. `NEXTGIN_INTERNAL_SECRET` is set on both sides. `nextgin.RequireInternal()` is a Gin middleware that 401s unless `X-Nextgin-Internal` matches (constant-time compare); with the secret unset it rejects every request. Server-side Next code calls the backend with `NEXTGIN_INTERNAL_URL` = `` and that header (small helper in `@nextgin/adapter`). The cron route keeps its own bearer (§3.4). ### 9.6 Cloudflare backend exposed publicly Combined mode sets `workers_dev: false` because only the service binding calls it. In split mode the generated wrangler config instead routes the `--backend-url` hostname as a custom domain and keeps `workers_dev: false`. ### 9.7 External data stores from wasm (spiked locally 2026-11-17) Spike: pgx v5.13.0 and go-redis v9.23.0 in the Go/wasm backend, using workers-go v0.36.0 `cloudflare/sockets` (a `net.Conn` over Workers `connect()`), under `wrangler dev` against local Postgres 16 and Redis 7. workers-go has no Hyperdrive binding. Works: - Postgres: `cfg.DialFunc` = a dialer calling `sockets.Connect`, and `cfg.LookupFunc` returning the host unchanged (Go wasm has no resolver). Plaintext and TLS both work; with `sslmode=require` pgx does the TLS handshake itself (crypto/tls in wasm; `show ssl` = on). Connect + query ~32-46 ms warm, 139-181 ms first request (local network). - Redis: go-redis `Options.Dialer` = the same dialer; INCR works. Required, found by ablation: - The dialer must call `sockets.Connect(context.WithoutCancel(ctx), ...)`. workers-go ties the socket's lifetime to the context passed to `Connect`, and go-redis cancels its dial context as soon as the dial returns, so the first read fails with `i/o timeout`. Not needed for pgx's default path, but harmless. (A wrapper mapping zero-time deadlines to the far future was also tried and is NOT needed.) Hard limit: - A connection cannot be reused across requests. The second request that touches a connection opened by an earlier request hangs and the runtime cancels it ("Worker's code had hung"); the next request then runs on a fresh instance. Open one connection per request and close it. For production, put a pooler in front (Neon/Supabase pooler, PgBouncer) so a per-request connection is cheap. Not verified: socket-native TLS (`SecureTransportOn`; it failed against a self-signed cert locally, so it says nothing about real certificates, and would avoid TLS CPU in wasm), real managed providers, behaviour under load, Upstash-style REST clients. Size: the spike (nextgin + pgx + go-redis, `-tags nomsgpack`, stripped) is 25.2 MB (the 10.0 MB example baseline plus ~15 MB), above the CLI's 20 MiB warning. How much is pgx vs go-redis was not measured, and the cold-start CPU of a 25 MB module was not measured. Helper (implemented): `nextgin.DialContext` and `nextgin.LookupHost` (`dial*.go`). On js/wasm `DialContext` is `sockets.Connect` with the detached context; elsewhere it is a plain `net.Dialer`. Same user code on every target: `cfg.DialFunc = nextgin.DialContext`, `cfg.LookupFunc = nextgin.LookupHost` (pgx), `Options.Dialer = nextgin.DialContext` (go-redis). Verified: native tests (echo, cancel-after-dial, rejection of non-tcp networks) and the wasm spike re-run on the helper under `wrangler dev` (Postgres insert+count, Redis INCR, counters matched). ### 9.8 Not in scope - Go caching rendered pages behind Vercel (Vercel's own cache sits in front; unproven). - Image resizing route (`images.loader`): container backend only, separate feature. - Leader election for multi-instance schedulers. ### 9.9 Verification Gate (§8) plus: API-only mode serves routes and runs a cron with no `dir`; `RequireInternal` and `CORS` tests (missing/wrong secret, disallowed origin, credentials); CLI tests for both `--api-mode` outputs and for no `crons` in split `vercel.json`; Docker build of the emitted Dockerfile. ### 9.10 Verified locally (2026-11-17) - `--backend-target container`: generated Dockerfile builds (golang:1.27 from go.mod, distroless nonroot, 27.6 MB image); the container serves the API, answers the cron route 401 without and 204 with `CRON_SECRET`, 404 on `/` (no frontend), no `[GIN-debug]` output. Limitation: the Dockerfile runs `go mod download` before `COPY . .`, so a local `replace` directive must be copied first (the CLI prints this); published modules are unaffected. - `--backend-target cloudflare`: 10.0 MB wasm, wrangler config has `routes: [{pattern, custom_domain: true}]`, `workers_dev: false`. - Combined `--target cloudflare` outputs are byte-identical to before. - Not yet verified: a real split deploy (Vercel web + Workers or container backend), Vercel external-rewrite billing, `direct` mode cookies/CORS in a browser, Postgres/Redis against managed providers and under load (§9.7). ## 10. `nextgin deploy` (single VPS, everything included) Status: implemented; verified with `--local` (§10.10) and over real SSH into a Debian 12 target container (§10.11); not yet on a real internet-facing VPS. Goal: `nextgin deploy` takes a project to a running VPS with no hand-written Docker, proxy or env files. The app runs in **self-host mode** (Go front door + Node workers, §4.1), not the API-only `backend` target. Postgres and Redis are created on the server and wired into the app's env automatically; the user is only asked for connection details when a database is external. (The command is `nextgin deploy`; the npm bin is `nextgin`.) ### 10.1 Command, config, flags `nextgin deploy [--host user@host | --local] [--name app] [--domain example.com] [--postgres internal|external|none] [--redis internal|external|none] [--reconfigure] [--dry-run] [--no-install-docker] [--ssh-port 22] [--identity ~/.ssh/key] [--dir /opt/nextgin] [--http-port 80] [--https-port 443]`. `--local` deploys to the machine the command runs on instead of over SSH: the same steps (build, image, `.env` merge, compose up, health check) with local process execution as the transport, no SSH, no OS check, no Docker install (Docker must already work for the current user). It exists for running `nextgin deploy` on the server itself and for testing without a VPS. `--dir` is the base directory (default `/opt/nextgin`, the app lives in `//`); `--http-port` / `--https-port` are the host ports compose publishes (defaults 80 / 443) so a test run does not collide with other services. `--local` and `--host` are mutually exclusive; one is required unless `nextgin.deploy.json` supplies `host`. Non-secret choices (`host`, `name`, `domain`, ssh port) are saved to `nextgin.deploy.json` in the project root after the first run, so later runs are just `nextgin deploy`. It never contains passwords or connection URLs. `--dry-run` writes the generated files to `.nextgin/deploy/` and prints the plan; it does not touch the network. ### 10.2 Project layout and build Two layouts, detected in this order: (a) split layout: `web/package.json` and `backend/go.mod` exist; (b) root layout: `package.json` and `go.mod` in the project root (as `examples/fullstack-app`). Otherwise fail with a message naming both. The CLI builds on the developer machine, not on the VPS and not in Docker (nextgin is private, a Go build in Docker fails on local `replace` directives and needs credentials; `next build` needs RAM small VPSes lack): 1. `ssh uname -m` -> arch (`x86_64` -> `amd64`, `aarch64` -> `arm64`, else fail). 2. Next build with the selfhost adapter in the web dir (split layout: cwd `web/`; root layout: cwd root), producing `.nextgin/`. 3. `CGO_ENABLED=0 GOOS=linux GOARCH= go build -trimpath -ldflags="-s -w" -o server .` in the backend dir. 4. If `.nextgin/server` contains any `*.node` native module and the build machine's arch differs from the VPS arch, fail with an explanation (no cross-arch native builds in v1). ### 10.3 Image Runtime-only Dockerfile (generated, first line is a `# generated by nextgin` marker, written to a temp build context with `server` and `.nextgin/`): `FROM node:22-bookworm-slim`, `WORKDIR /app`, `COPY server .nextgin` into it, `ENV PORT=8080 GIN_MODE=release`, `USER node`, `EXPOSE 8080`, `HEALTHCHECK` via `node -e fetch(...)` to `http://127.0.0.1:8080/` (healthy when status < 500), `ENTRYPOINT ["/app/server"]`. Built locally with `docker build --platform linux/` and shipped without a registry: `docker save | gzip | ssh "gunzip | docker load"`. Tag `nextgin-:` plus `:latest`; the remote keeps the last 3 tags and prunes older ones of this name only. ### 10.4 Stack (`docker-compose.yml`, generated, marker line first) Remote dir `/opt/nextgin//` holds `docker-compose.yml`, `.env` (mode 600) and, with a domain, `Caddyfile`. Services: - `app`: the image, `env_file: .env`, `restart: unless-stopped`, `depends_on` each internal database with `condition: service_healthy`. Published as `:8080` (default 80) when there is no domain; not published when Caddy is present. - `postgres` (only when internal): `postgres:16`, named volume, env `POSTGRES_USER=nextgin`, `POSTGRES_DB= _>`, `POSTGRES_PASSWORD` from `.env`, healthcheck `pg_isready`. NO `ports:`. - `redis` (only when internal): `redis:7`, `--requirepass` from `.env`, `--appendonly yes`, named volume, healthcheck `redis-cli ping`. NO `ports:`. - `caddy` (only with `--domain`): `caddy:2`, publishes `:80` and `:443`, mounts `Caddyfile`, volumes for data/config. Caddyfile: ` { reverse_proxy app:8080 }` (automatic HTTPS; the DNS record must already point at the VPS; print that reminder). Docker-published ports bypass ufw, hence no database ports. Images are pinned to a major version (a major bump breaks an existing volume). The tool never runs `down -v`, never deletes volumes. ### 10.5 `.env` rules (remote file is the source of truth) - Keys the app receives: `DATABASE_URL`, `REDIS_URL` (when not `none`), plus `NEXTGIN_POSTGRES` and `NEXTGIN_REDIS` recording `internal|external| none` so later runs do not ask again. - Internal values use service names, so no host ports are needed: `DATABASE_URL=postgres://nextgin:@postgres:5432/?sslmode=disable`, `REDIS_URL=redis://:@redis:6379/0`. Passwords are 48 hex chars from `crypto.randomBytes(24)` (URL-safe). Compose reads `POSTGRES_PASSWORD` and `REDIS_PASSWORD` from the same file. - Secrets are generated ONCE. On every deploy the CLI downloads the remote `.env`, keeps every existing key and value, adds only missing keys, and uploads it with mode 600. A password is never regenerated (Postgres applies `POSTGRES_PASSWORD` only when it first initialises the volume). - External: the CLI prompts for the URL (hidden input), writes it to `.env`, and omits that service from the compose file. URLs are never accepted as command-line arguments (shell history, `ps`); non-interactive runs read `DATABASE_URL` / `REDIS_URL` from the local environment instead and fail if missing. - Switching internal -> external leaves the old volume untouched and prints a warning with the volume name. ### 10.6 Prompts Only for services the app uses, detected from the backend `go.mod`: Postgres if it requires `github.com/jackc/pgx`, `github.com/lib/pq` or `gorm.io/driver/postgres`; Redis if it requires `github.com/redis/go-redis` or `github.com/gomodule/redigo`. Neither detected -> no database services and no prompts. For each detected service whose `NEXTGIN_POSTGRES|REDIS` key is absent from the remote `.env`: `Postgres: create one on this server? [Y/n]` (Enter = internal); on `n`, prompt for the external URL (hidden). `--postgres` and `--redis` answer without prompting; `--reconfigure` asks again. No TTY and no flag -> internal, with external requiring the flag plus env var. ### 10.7 Remote steps (idempotent) 1. SSH check (`BatchMode=yes`, `ConnectTimeout=10`, `StrictHostKeyChecking` left at the user's ssh default). Host key problems are surfaced, not bypassed. 2. OS check: Debian or Ubuntu or a derivative (`ID` or `ID_LIKE` in `/etc/os-release` contains `debian` or `ubuntu`), and root or passwordless sudo; otherwise fail with a precise message. Skipped with `--local`. 3. Docker: if `docker compose version` fails, install with Docker's official convenience script (`curl -fsSL https://get.docker.com | sh`) unless `--no-install-docker`, which fails with instructions instead. 4. `mkdir -p /opt/nextgin/`, upload compose, Caddyfile, merged `.env` (mode 600), load the image, `docker compose up -d --remove-orphans`. 5. Wait up to 120 s for the app container to be healthy, then print the URL (`https://` or `http://[:]`). On failure print the last 50 log lines of the unhealthy service and exit non-zero; leave the stack up. ### 10.8 Known limits (v1) - Single host, single app instance; the scheduler (§3.5) runs in it. - Recreate causes brief downtime; no rollback command (previous images stay). - No Postgres backups. Documented, not solved. - Behind Caddy, Go sees the proxy as the client: set `Config.TrustForwardedHeaders: true` in `main.go` (not controlled by the CLI). - Debian/Ubuntu family only (remote); Docker only; no Windows-hosted VPS. ### 10.9 Code layout and verification Pure generators (no I/O) in `packages/adapter/src/deploy/`: `generate.ts` (Dockerfile, compose, Caddyfile), `env.ts` (parse, merge, secret generation), `detect.ts` (layout, services from go.mod), `config.ts` (`nextgin.deploy.json`). I/O in `ssh.ts` (system `ssh`/`scp`, argv arrays, no shell interpolation of user input) and `command.ts` (flow). Verification without a VPS: unit tests of the generators; `--dry-run`; run the generated compose stack locally under an `ng-` project name (app route using `DATABASE_URL`/`REDIS_URL` through `nextgin.DialContext`), then redeploy without `-v` and confirm data and passwords survive; external mode against a separate container. A real VPS run needs the user's explicit approval. ### 10.10 Verified locally (2026-11-17, `--local`, Docker Compose v5.7) Test app: the example plus a route that increments a counter in Postgres (pgx) and Redis (go-redis) from `DATABASE_URL` / `REDIS_URL`, via `nextgin.DialContext`. Run with `--dir --http-port 18180`. - First deploy (no prompts, services detected from go.mod): app healthy, `/api/dbcheck` incremented both stores through the auto-wired URLs, prerendered and SSR pages served; Postgres/Redis publish no host ports (`5432/tcp`, `6379/tcp` only); `.env` mode 600; the app runs as the `node` user; `nextgin.deploy.json` holds no secrets. - Redeploy: `.env` byte-identical, the Postgres container not recreated, data persisted (counters 2 -> 3), nothing asked, previous image kept. - External Postgres (`--postgres external`, URL from `DATABASE_URL` env, the password containing `$`): no Postgres service generated, the URL stored with `$$`, the app connected to the external database. - `--domain app.localhost` with custom ports: Caddy up, HTTPS 200 through the proxy, database check passed through it. - `--dry-run`: preview files written, secrets shown as ``, no build. - Interactive prompts (pseudo-terminal): answering `n` switches a service to external and asks for a hidden URL. Input fed faster than a person types loses lines (readline is recreated per prompt); not an issue when typing. - Review found and fixed: the SSH image upload ran plain `docker load` when the remote user needs `sudo -n docker`; `loadImage` now takes the docker command. The success URL now includes a non-default HTTPS port. Not verified: a real SSH deploy (the host had no sshd and no passwordless sudo), Docker installation on a fresh VPS, arm64 targets, apps with native `.node` modules, `--reconfigure` end to end, large `.nextgin` trees with symlinks, Let's Encrypt issuance. ### 10.11 Verified over SSH (2026-11-18) Target: a `debian:12` container with `openssh-server`, run `--privileged` with a tmpfs `/var/lib/docker` on this machine, reached as `127.0.0.1:2222`. No Docker installed beforehand, and no systemd. Key auth only (`--identity`). - Non-root user with passwordless sudo: the OS check passed, Docker was installed by `get.docker.com`, the image was uploaded with `sudo -n docker load`, and the stack came up. `/api/dbcheck` incremented Postgres and Redis, prerendered and SSR pages returned 200, `.env` is mode 600, Postgres and Redis publish no host ports, and `nextgin.deploy.json` holds host, name and ssh port only. - Redeploy with only `--identity` (host, name and port read from the saved config): `.env` hash and the Postgres/Redis container ids unchanged, counters continued (2 -> 3), the previous image kept. - `root@`: plain `docker` (no sudo), a second stack on another port, healthy. - Bug found by this run and fixed: if the remote `docker load` failed (daemon not running), ssh exited while the local `docker save` blocked forever writing into a pipe nobody read, so the CLI hung without an error. The upload now fails at once with ssh's error; regression test `test/transport-load.test.mjs` (fails with a 15 s hang without the fix). - Not covered by this run: a systemd host (the daemon was started by hand, because the container has no init system, so the installer's service start is unproven), arm64, a real network, firewalls, Let's Encrypt, and a first-time host-key prompt (BatchMode is on: the host key must already be in `known_hosts`, so connect once with plain `ssh` first).