nextgin
Run a Next.js app with a pure-Go (net/http) API and cron backend — zero web-framework overhead (~7.5 MB native binary) — and deploy it either as a lightweight split sidecar (Vercel web + Go container) or all-in-one on your own VPS (nextgin deploy).
- Pure Go
net/httprouter:Routerwraps Go 1.22+http.ServeMuxwithGroup,With,Middleware, panic recovery, JSON/raw-body helpers (ReadJSON,ReadRawBody,WriteJSON), per-IPRateLimit, and secureSetSessionCookie/ClearSessionCookie. - Crons are routes:
app.Cron("name", "*/5 * * * *", handler)registers/_nextgin/cron/<name>and runs in-process onbackend/selfhost(no Vercel Hobby daily-cron limits), with graceful shutdown cancellation and an optionalCronLockerhook for rolling deploys. - Go is the front door on self-host: Serves static assets, prerendered pages,
next.configheaders/redirects, and your API routes natively, proxying only dynamic pages (SSR, RSC, Server Actions) to Node/Bun workers. - Built-in liveness probe:
GET /_nextgin/healthanswers200 {"status":"ok"}without touching Next.js or appearing in exported API routes.
Status: pre-release (0.1.0), private repository, not published to npm. Details and measurements: docs/SPEC.md.
Recommended: Split Topology (Next.js on Vercel + Tiny Go API/Cron Container)
Keep Next.js on Vercel for UI/SSR while a tiny distroless Go container (on Fly.io, Cloud Run, Railway, or a $4–5/mo VPS) handles auth, cart, payments, webhooks, and sub-minute crons:
// backend/main.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)
}
// Browser calls https://api.example.com directly (default --api-mode direct).
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, issue 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)
})
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 HMAC signature with your payment provider
w.WriteHeader(http.StatusOK)
})
// Unlimited crons — runs in Go, zero Vercel Cron invocations.
app.Cron("expire-carts", "* * * * *", func(w http.ResponseWriter, r *http.Request) {
// r.Context() is cancelled on SIGTERM for graceful shutdown.
w.WriteHeader(http.StatusNoContent)
})
app.MountFrontend() // no-op on NEXTGIN_TARGET=backend
log.Fatal(app.Run(":" + os.Getenv("PORT")))
}
Build the split config (web/vercel.json + backend/Dockerfile):
nextgin build --web-target vercel --backend-target container --backend-url https://api.example.com
--api-mode direct(default):web/vercel.jsonhas no external rewrites; the browser callsNEXT_PUBLIC_NEXTGIN_API_URLdirectly so API traffic bypasses Vercel compute/bandwidth. Usenextgin.CORS(...)and parent-domain cookies (Domain: ".example.com").--api-mode rewrite: opt-in same-origin mode that writes external rewrites intoweb/vercel.json.- Protect server-to-server routes called from Next.js SSR/Server Actions with
nextgin.RequireInternal()andNEXTGIN_INTERNAL_SECRET. - For rolling deploys or multiple replicas, plug a Postgres advisory lock or Redis
SET NXintoConfig.CronLocker(or setNEXTGIN_SCHEDULER=offon replicas).
Quick start (self-host / VPS)
Scaffold a new project with the 3-layer Go architecture (internal/domain, store, service, httpapi) and Next.js lib/api.ts:
npx @nextgin/adapter init my-app # single-repo selfhost layout
npx @nextgin/adapter init my-app --layout split # web/ + backend/ split layout
Or add the adapter to an existing Next.js app:
// next.config.mjs
import { createNextGinAdapter } from '@nextgin/adapter'
export default { adapterPath: createNextGinAdapter() }
nextgin build # next build, finalize .nextgin, go build -o server
./server
nextgin dev # next dev + Go server with restart on .go changes
Or ship everything (Go + Node workers + Postgres/Redis + Caddy HTTPS) to a single VPS:
nextgin deploy --host root@203.0.113.7 --domain shop.example.com
- Databases: Postgres and Redis are detected from
go.mod. First deploy asks once per service whether to run it on the server (Enter = yes) or use an external URL; secrets are generated once into/opt/nextgin/<name>/.env(mode 600) and preserved across redeploys. - Local / dry-run:
nextgin deploy --localruns on the current machine;--dry-runpreviews generated files in.nextgin/deploy/.
All Deployment Targets
| Mode | Command | Where things run | Notes |
|---|---|---|---|
| Split (recommended) | nextgin build --web-target vercel --backend-target container --backend-url https://api.example.com | Next.js on Vercel, Go container on your host | Zero Vercel API/cron invocations; full DB pooling |
| Self-host / VPS | nextgin build / nextgin deploy | One Go binary + Node/Bun workers | Go serves static/prerendered/API/crons natively |
| Vercel (combined) | nextgin build --target vercel | Next.js + Go service both on Vercel | Generates root vercel.json; Hobby allows daily crons only (--vercel-hobby) |
Security & Hardening Defaults
- Body limits:
ReadJSONcaps reads at 1 MiB (DefaultMaxBodyBytes) and rejects trailing data; useReadJSONLimitorReadRawBodyfor custom caps. - Server timeouts:
backend/verceltargets default toReadHeaderTimeout: 10s,ReadTimeout: 15s,WriteTimeout: 30s,IdleTimeout: 60s(selfhostleavesWriteTimeout: 0so SSR streaming is never cut off). - Fail-closed auth: Cron routes require the process-internal bearer token or
CRON_SECRET;RequireInternalrejects all traffic whenNEXTGIN_INTERNAL_SECRETis unset;CORSpanics on empty or*allow-lists.
Development
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
docs/PATTERNS.md covers app folder structure, separation of concerns (httpapi → service → store), API/error patterns, middleware, and the Next.js ↔ Go client boundary. docs/COOKBOOK.md covers deployment topology, database/ORM choices, auth, webhooks, and cron locking. AGENTS.md is the contributor & AI-agent guide. docs/SPEC.md is the design record.