@constructive-io/graphql-server
v5.37.2
Published
Constructive GraphQL Server
Readme
@constructive-io/graphql-server
Constructive GraphQL Server is an Express-based server built on PostGraphile. It reads Constructive metadata to select API schemas, applies RLS-aware auth, and exposes a production-ready GraphQL API.
🚀 Quick Start
Use as SDK
Install the package:
pnpm add @constructive-io/graphql-server @constructive-io/graphql-envStart a server:
import { getEnvOptions } from '@constructive-io/graphql-env';
import { GraphQLServer } from '@constructive-io/graphql-server';
GraphQLServer(
getEnvOptions({
pg: { database: 'constructive_db' },
server: { host: '0.0.0.0', port: 3000 },
})
);Tip: Set
PGHOST,PGPORT,PGUSER,PGPASSWORD,PGDATABASEto control DB connectivity. See Configuration for the full list of supported env vars and defaults.
Local Development (this repo)
pnpm install
cd graphql/server
pnpm devThis starts the server with env defaults from @constructive-io/graphql-env.
Tip: Set
PGHOST,PGPORT,PGUSER,PGPASSWORD,PGDATABASEto control DB connectivity. See Configuration for the full list of supported env vars and defaults.
What it does
Platform deployments connect through one pgpm-provisioned NOSUPERUSER INHERIT
NOBYPASSRLS login, configured only with PGUSER/PGPASSWORD. Startup and
routing queries run as that login, so rows behind member RLS stay hidden from
it: standing and routing settings are read through static, login-only
SECURITY DEFINER readers in function_resolution. Requests switch to
authenticated or anonymous, so PostgreSQL enforces their RLS policies.
Runs an Express server that wires CORS, uploads, domain parsing, auth, and PostGraphile into a single GraphQL endpoint. It serves /graphql and /graphiql, injects per-request pgSettings, and flushes cached schemas on demand or via database notifications. When meta API is enabled, it resolves API config (schemas, roles, modules) from the meta schema using the request host and enforces api.isPublic, with optional header overrides in private mode; when meta API is disabled, it serves the fixed schemas and roles from api.exposedSchemas, api.anonRole, and api.roleName.
Key Features
- Automatic GraphQL API generation from PostgreSQL schemas
- RLS-aware authentication and per-request
pgSettings - Meta-schema routing by domain + subdomain
- GraphiQL and health check endpoints
- Schema cache flush via
/flushor database notifications - Opt-in observability for memory, DB activity, and Graphile build debugging
Schema notification recovery
GraphQLServer() starts a dedicated LISTEN "schema:update" session. When
embedding Server directly, call addEventListener() once; repeated calls
coalesce. Close it with await server.close() during shutdown.
The listener reconnects after connection errors, connection end, or a stalled query. It probes the held session every 30 seconds, gives LISTEN and each probe 5 seconds to finish, and retries connections after 5 seconds. Failed sessions are destroyed instead of returned to the query pool. Shutdown cancels retries and does not wait for an unresponsive session to acknowledge UNLISTEN.
After LISTEN succeeds, the process invalidates all routing, GraphQL handler, and storage discovery caches. PostgreSQL does not replay notifications missed while disconnected. In-flight lookups and handler builds from before the invalidation cannot repopulate those caches; affected requests resolve again. Recovery can therefore cause a temporary burst of schema rebuilds.
A connected and listening for changes; invalidated all services log confirms
successful subscription and invalidation. Subsequent schema:update messages
use the normal per-database flush. If that flush fails, all caches are
invalidated conservatively and the failure is logged.
Observability
@constructive-io/graphql-server includes an opt-in observability mode for local debugging.
- Master switch:
GRAPHQL_OBSERVABILITY_ENABLED=true - Debug routes:
GET /debug/memory,GET /debug/db - Background sampler: periodic NDJSON snapshots under
graphql/server/logs/ - CLI helpers:
pnpm debug:memory:analyzepnpm debug:heap:capture
Observability only activates when all of the following are true:
GRAPHQL_OBSERVABILITY_ENABLED=trueNODE_ENV=development- the server is bound to a loopback host such as
localhost,127.0.0.1, or::1
When those conditions are not met, the debug routes are not mounted and the sampler does not start. This keeps the default runtime surface minimal and prevents the observability layer from being exposed remotely.
For the operational workflow, sampler output, and heap snapshot usage, see docs/memory-debugging.md.
Routes
GET /healthz-> health checkGET /graphiql-> GraphiQL UI (disabled by default whenNODE_ENV=production; override withGRAPHILE_GRAPHIQL)GET /graphql/POST /graphql-> GraphQL endpointPOST /flush-> clears cached Graphile schema for the current API; mounted only whenAPI_FLUSH_TOKENis set, and requiresAuthorization: Bearer $API_FLUSH_TOKEN. Without the variable the route is not served (404) — operators deploying a schema-cache flush must set it on the server and on every caller. TheLISTEN/NOTIFYinvalidation path is unaffected.GET /debug/memory-> memory/process/Graphile debug snapshot when observability is enabledGET /debug/db-> PostgreSQL activity/locks/pool debug snapshot when observability is enabled
Auth cookies and CSRF
Browsers authenticate with the constructive_session cookie; every other client sends Authorization: Bearer <accessToken>.
- A successful sign-in mutation (
signIn,signInSso,signInMagicLink,signInEmailOtp,completeMfaChallenge, …) returns the access token in the response body and also setsconstructive_session(plusconstructive_device_tokenwhen the mutation returns a device id).Max-Agecomes from the API's auth settings (default 86400 s;rememberMe: trueuses the remember-me duration). signUpnever signs anyone in: it returns no access token and sets no session cookie, so its answer is the same whether or not the address already has an account. Verify the email (verifyEmail), then callsignIn.signOutalways answers with expiredconstructive_sessionandconstructive_device_tokencookies (Max-Age=0), however the request authenticated and whether or not the mutation succeeded.revokeSession/revokeAllSessionsclear them on success.- Every request gets a
csrf_tokencookie (readable by JS, one day). APOST /graphqlthat carriesconstructive_sessionand no Bearer header must echo that value inX-CSRF-Token, or it is refused with 403CSRF_TOKEN_MISSING/CSRF_TOKEN_INVALID. Bearer requests and requests without a session cookie skip the check.
Non-browser clients (native apps, CLIs, servers)
Send X-Constructive-Session-Cookie: omit on every request. Sign-in mutations then set no auth cookie: read accessToken from the response body and send it as Authorization: Bearer <accessToken>. Any other value of the header is refused with 400 INVALID_SESSION_COOKIE_HEADER before the operation runs. The header does not bypass CSRF: a request that still carries constructive_session without a Bearer header is checked like a browser's, so sign out with the Bearer token (its response expires any session cookie the client was given before it opted out).
Scoped routing
This is a production-only server: every request is resolved through the scoped-routing plane. There is no static single-tenant mode and no flag to disable routing. For single-database local development without route resolution or a database id, use @constructive-io/graphql-dev-server.
- The server resolves the request host with a single
resolve_route()call against the compiled route bindings inrouting_public, mapping host → tenant/api/database/role. - Only APIs where
api.is_publicmatchesAPI_IS_PUBLICare served. - In private mode (
API_IS_PUBLIC=false), you can override with headers:X-Api-Name+X-Database-IdX-Schemata+X-Database-IdX-Meta-Schema+X-Database-Id
- A resolved database id is always required. There is no default database, so a request that resolves without a database id is rejected (
NO_DATABASE_ID→ HTTP 500).
Configuration
Configuration is merged from defaults, config files, and env vars via @constructive-io/graphql-env. See graphql/env/README.md for the full list and examples.
| Env var | Purpose | Default |
| ------------------------------ | ------------------------------------- | ------------------------------------------------------------- |
| PGHOST | Postgres host | localhost |
| PGPORT | Postgres port | 5432 |
| PGUSER | Postgres user | postgres |
| PGPASSWORD | Postgres password | password |
| PGDATABASE | Postgres database | postgres |
| GRAPHILE_SCHEMA | Comma-separated schemas to expose | empty |
| GRAPHILE_GRAPHIQL | Serve /graphiql UI and static assets | false when NODE_ENV=production, true otherwise |
| FEATURES_SIMPLE_INFLECTION | Enable simple inflection | true |
| FEATURES_OPPOSITE_BASE_NAMES | Enable opposite base names | true |
| FEATURES_POSTGIS | Enable PostGIS support | true |
| API_IS_PUBLIC | Serve public APIs only | true |
| API_EXPOSED_SCHEMAS | Additional schemas to expose | empty |
| API_META_SCHEMAS | Meta schemas to query | routing_public,metaschema_public,metaschema_modules_public |
| API_ANON_ROLE | Anonymous role name | administrator |
| API_ROLE_NAME | Authenticated role name | administrator |
| API_FLUSH_TOKEN | Bearer token required by POST /flush; route is not mounted when unset | empty |
| API_INTROSPECTION_ROLE | Role PostGraphile introspects as; unset means the pool's connecting role. Naming a role with fewer grants removes fields from the schema | empty |
| GRAPHQL_OBSERVABILITY_ENABLED | Master switch for debug routes and sampler | false |
| GRAPHQL_DEBUG_SAMPLER_ENABLED | Enables periodic NDJSON sampling when observability is on | true |
| GRAPHQL_DEBUG_SAMPLER_INTERVAL_MS | Sampler interval in milliseconds | 10000 |
| GRAPHQL_DEBUG_SAMPLER_DIR | Override output directory for sampler logs | graphql/server/logs |
Testing
Use supertest or your HTTP client of choice against /graphql. For RLS-aware tests, provide a Bearer token and ensure the API's auth function is available.
Related Packages
@constructive-io/graphql-env- env parsing + defaults for GraphQL@constructive-io/graphql-types- shared types and defaultsgraphile-settings- PostGraphile configurationgraphile-meta-schema- meta schema support
Education and Tutorials
🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.
📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.
🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
⚡ Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.
Related Constructive Tooling
📦 Package Management
- pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
🧪 Testing
- pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
- pglite-test: 🪶 Drop-in pgsql-test replacement backed by PGlite — in-process Postgres, no server required, instance-per-suite isolation.
- pgsql-seed: 🌱 PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
- supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
- graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
- pg-query-context: 🔒 Session context injection to add session-local context (e.g.,
SET LOCAL) into queries—ideal for settingrole,jwt.claims, and other session settings.
🧠 Parsing & AST
- pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
- libpg-query-node: 🌉 Node.js bindings for
libpg_query, converting SQL into parse trees. - pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
- @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
- @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
- @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.
📚 Documentation & Skills
- constructive-skills: 📖 Platform documentation and AI agent skills — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
Install skills for AI coding agents:
# All platform skills (security, blueprints, codegen, billing, etc.)
npx skills add constructive-io/constructive-skills
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
npx skills add constructive-io/constructive --skill pgpm
npx skills add constructive-io/constructive --skill safegres
npx skills add constructive-io/constructive --skill constructive-testingCredits
🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.
Disclaimer
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
