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.
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.
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.
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.
- 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
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.
@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.
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
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.
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).
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 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 |
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.
@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