npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-env

Start 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, PGDATABASE to 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 dev

This starts the server with env defaults from @constructive-io/graphql-env.

Tip: Set PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE to 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 /flush or 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:analyze
    • pnpm debug:heap:capture

Observability only activates when all of the following are true:

  • GRAPHQL_OBSERVABILITY_ENABLED=true
  • NODE_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 check
  • GET /graphiql -> GraphiQL UI (disabled by default when NODE_ENV=production; override with GRAPHILE_GRAPHIQL)
  • GET /graphql / POST /graphql -> GraphQL endpoint
  • POST /flush -> clears cached Graphile schema for the current API; mounted only when API_FLUSH_TOKEN is set, and requires Authorization: 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. The LISTEN/NOTIFY invalidation path is unaffected.
  • GET /debug/memory -> memory/process/Graphile debug snapshot when observability is enabled
  • GET /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 sets constructive_session (plus constructive_device_token when the mutation returns a device id). Max-Age comes from the API's auth settings (default 86400 s; rememberMe: true uses the remember-me duration).
  • signUp never 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 call signIn.
  • signOut always answers with expired constructive_session and constructive_device_token cookies (Max-Age=0), however the request authenticated and whether or not the mutation succeeded. revokeSession / revokeAllSessions clear them on success.
  • Every request gets a csrf_token cookie (readable by JS, one day). A POST /graphql that carries constructive_session and no Bearer header must echo that value in X-CSRF-Token, or it is refused with 403 CSRF_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 in routing_public, mapping host → tenant/api/database/role.
  • Only APIs where api.is_public matches API_IS_PUBLIC are served.
  • In private mode (API_IS_PUBLIC=false), you can override with headers:
    • X-Api-Name + X-Database-Id
    • X-Schemata + X-Database-Id
    • X-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 defaults
  • graphile-settings - PostGraphile configuration
  • graphile-meta-schema - meta schema support

Education and Tutorials

  1. 🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.

  2. 📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.

  3. ✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.

  4. 🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.

  5. ⚡ Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.

  6. 💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.

  7. 🔧 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 setting role, 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-testing

Credits

🛠 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.