Skip to Content
GraphQLNative API

Native GraphQL API

native.makeSchema serves a GraphQL API generated from your schema.cyphra and run by the typed client: every root field is one client operation (findMany, findUnique, …), compiled to one Cypher statement, so filters, ordering, paging, writes and errors behave the same from TypeScript and from GraphQL. What the API exposes is configured in TypeScript, typed against the generated client.

Experimental (see the stability policy): the native API may change in a minor release. This release serves reads (findUnique, findFirst, findMany, count), writes (create, createMany, update, updateMany, upsert, delete, deleteMany, off by default) and auth (rules compiled into the statement, field rules, authenticated). Nested update / delete / upsert, aggregates, search and traversals come next (#77 ). Relay Node is opt-in (below). To keep the API @neo4j/graphql v7 generates, use compat.v7; both can be served side by side.

Create the schema

npm i @cyphra/graphql graphql
lib/graphql.ts
import { native } from "@cyphra/graphql"; import { createClient } from "./cyphra.gen"; import { api } from "./graphql.config"; const db = createClient({ uri, user, password }); export const schema = native.makeSchema({ client: db, config: api });

makeSchema returns a GraphQLSchema with its resolvers: serve it with GraphQL Yoga, Apollo Server or any GraphQL server.

OptionDescription
clientThe client of cyphra.gen.ts (possibly $extends-ed), or a function of the GraphQL context returning the request’s client: (ctx) => db.$extends(…).
schemaThe schema model. Default: client.$schema. Required when client is a function.
configThe API’s configuration, from defineGraphQL (below). Default: every read operation of every model, no writes.
debugShow the message of unexpected errors instead of Internal server error.

With a function as client, every root field runs through that request’s client, so the client’s query hooks run (multi-tenancy, soft delete, audit logs). Hooks wrap the root operation only, as in the client.

Configure it

graphql.config.ts
import { defineGraphQL } from "@cyphra/graphql/native"; import type { CyphraTypeMap } from "./cyphra.gen"; export const api = defineGraphQL<CyphraTypeMap>({ models: { User: { fields: { passwordHash: false, // gone from every type and input email: { filter: false, sort: false }, // readable, not usable in where / orderBy }, }, AuditLog: { operations: { read: ["findMany", "count"] } }, Session: { operations: { read: false } }, Post: { operations: { create: true, update: true, delete: ["delete"] } }, }, naming: { Person: { findMany: "people" } }, limits: { maxDepth: 4, maxTake: 100, maxAliases: 20, maxComplexity: 10_000 }, });

Every key is typed from CyphraTypeMap: { pasword: false } or a model that does not exist is a compile error. makeSchema checks the config again at startup (for JavaScript, or configs built dynamically) and throws a NativeSchemaError naming the unknown model, field or option. It also refuses a model whose create is on while a required field without a default cannot be set (fields: { passwordHash: false } with create: true), create on an interface and writes on a union.

KeyDescription
models.<M>.operationsPer group, true, false or a list of operations: read (findUnique, findFirst, findMany, count), create (create, createMany, upsert), update (update, updateMany, upsert), delete (delete, deleteMany). upsert is served when both create and update include it. Turning an operation off removes its root field.
models.<M>.fields.<f>false hides the field everywhere, writes included. { read, filter, sort, create, update } toggle reading it, filtering and sorting on it, and setting it in create / update inputs (for a relation: its nested writes). { read: false, create: true } is a write-only field. read may also be a field rule. { deprecated: "reason" } emits @deprecated. A toggle on an interface applies to its implementations.
models.<M>.rulesRow-level rules, compiled into every statement that reaches the model.
models.<M>.authenticatedOperations that need an authenticated request (authenticated).
isAuthenticated(ctx) => boolean: whether a request is authenticated. Default: the context has a user or a jwt.
defaults.operationsThe default of every model, per group. Reads are on, writes off.
naming.<M>.<operation>A root field name replacing <model><Operation> (reads and writes). It is part of the printed contract.
relaytrue adds Relay’s Node interface and node(id) (Relay). Off by default.
limitsChecked before the statement is built (see Limits).
mutationTransaction"field" (default): each mutation root field is its own transaction. "request": every root field of a mutation operation in one transaction (see Transactions).
generatorThe generator version the printed SDL follows. Only 1 today.

Naming

Root fields are <model><Operation>: no pluralization, and the fields of a model sort together. node BlogPost gives blogPostFindMany and blogPostCreate. Types keep the model names; inputs are <Model>Where, <Model>WhereUnique, <Model>OrderBy, <Model>CreateInput, <Model>UpdateInput; filters are shared per scalar type (StringFilter, IntFilter, DateTimeFilter, …).

GraphQL names cannot contain $, so the client’s $ keys become _ keys:

ClientGraphQL
db.post.findMany(args)postFindMany(...)
select / includethe selection set
$edge_edge
$labels_labels
$on in where_on
$on in selectinline fragments: ... on Employee { salary }
__typename in where / orderBy_typename
where: { email: "a@x.io" } (bare value)where: { email: { equals: "a@x.io" } }
orderBy: { createdAt: "desc" }orderBy: [{ createdAt: desc }]
data: { views: { increment: 1 } }data: { _ops: { views: { increment: 1 } } }

A model field named like one of these (_edge, _count, _labels, _on, _typename, _score, _scores, _ops) is a makeSchema error: rename it in schema.cyphra.

Queries

type Query { userFindUnique(where: UserWhereUnique!): User userFindFirst(where: UserWhere, orderBy: [UserOrderBy!], skip: Int): User userFindMany( where: UserWhere orderBy: [UserOrderBy!] skip: Int take: Int after: String before: String ): UserList userCount(where: UserWhere): Int } type UserList { nodes: [User!]! pageInfo: PageInfo! totalCount: Int! }
  • userFindUnique takes the model’s @id / @unique fields as bare values (and @@unique keys as objects), plus filters on the other fields. At least one key is required: a where without one is a BAD_USER_INPUT error.
  • Root fields are nullable: a failing root field is null with its error, and the other root fields of the query still return.

Lists and paging

There is one list query per model, for offset and cursor paging:

query Feed($after: String) { postFindMany( where: { published: { equals: true } } orderBy: [{ createdAt: desc }] take: 20 after: $after ) { nodes { id title author { name } } pageInfo { hasNextPage endCursor } totalCount } }
  • skip / take page by offset; after / before page by cursor, after or before a pageInfo.endCursor / startCursor. after with skip skips within the page after the cursor.
  • Cursors are keyset cursors (the client’s cursor): the orderBy values of the boundary node and its @id. A page after a cursor does not shift when nodes are inserted before it. A cursor made for another orderBy or another model, or a malformed one, is a BAD_USER_INPUT error, never the first page.
  • pageInfo loads one row more than take to tell whether there is a next page (a previous one with before). Paging forward, hasPreviousPage is true when after or skip is given.
  • totalCount (the number of nodes matching where) is only counted when selected, in the same read transaction as the page.

Filters

<Model>Where mirrors the client’s where:

query { userFindMany( where: { OR: [{ role: { equals: ADMIN } }, { email: { endsWith: "@acme.io", mode: insensitive } }] posts: { some: { published: { equals: true } } } name: null } ) { nodes { email } } }
  • Operators are the client’s (table): equals, not, in, notIn, lt, lte, gt, gte, contains, startsWith, endsWith, mode: insensitive; list fields take has, hasEvery, hasSome, isEmpty, equals; points take distance and withinBBox.
  • name: null and { equals: null } match nodes without the property; { not: null } the others.
  • To-many relations take some, none, every; some: {} means “has at least one”. To-one relations take is, isNot; author: null means “has none”.
  • Vector fields cannot be filtered or sorted on (use the client’s findSimilar).

Ordering

orderBy is a list with one key per element (input object field order is not reliable in every client library); two keys in one element are a BAD_USER_INPUT error.

orderBy: [ { author: { name: asc } } # to-one: a field of the related node { tags: { _count: desc, where: { name: { startsWith: "a" } } } } # to-many: their number { createdAt: desc } ]

Point fields sort by distance: { location: { distanceFrom: { longitude: 2.35, latitude: 48.85 } } }.

Relations, _edge and _count

To-many relations take where, orderBy, skip and take, as a nested include of the client; to-one relations are nullable objects. The same relation can be loaded twice under aliases, still in one statement:

query { userFindUnique(where: { email: "alice@acme.io" }) { recent: posts(orderBy: [{ createdAt: desc }], take: 3) { title } popular: posts(orderBy: [{ views: desc }], take: 3) { title } following(orderBy: [{ name: asc }]) { name _edge { since } } _count { posts followers(where: { role: { equals: ADMIN } }) } } }
  • Edge properties of a relation with a relationship { … } model are the _edge field of the node it leads to: no connection types. Selecting _edge on a node that was not reached through such a relation (a root, or another relation) is a BAD_USER_INPUT error, not a silent null. When several relationship models lead to a node, _edge is a union of them (union UserEdge = Blocks | Follows), selected with inline fragments.
  • _count counts the related nodes of each selected to-many relation (only those), optionally filtered. A relation can be counted once per selection.

Interfaces and unions

Cyphra interfaces (a label shared by their implementations) are GraphQL interfaces; unions are GraphQL unions. Inline fragments and fragment spreads are the client’s $on: each implementation’s selection is evaluated only on its nodes, in the same statement.

query { personFindMany( where: { _on: { Employee: { salary: { gt: 100 } }, Customer: {} } } orderBy: [{ _typename: asc }, { name: asc }] ) { nodes { __typename name manager { name } ... on Employee { salary } } } customers: personCount(where: { _typename: { in: [Customer] } }) }
  • _typename filters and sorts by implementation (an enum of them); _on keeps the listed implementations matching their own where.
  • A union has findFirst, findMany and count (no unique key, so no findUnique).
  • An interface without fields (interface Archivable {}) is served as a union of its implementations: GraphQL interfaces need at least one field.

Mutations

Writes are off by default: a model is writable through the API once its config turns them on (operations: { create: true, update: true, delete: true }, or a list per group). Each operation is one root field of Mutation, run as one client operation:

type Mutation { postCreate(data: PostCreateInput!): Post postCreateMany(data: [PostCreateManyInput!]!): PostBatch postUpdate(where: PostWhereUnique!, data: PostUpdateInput!): Post postUpdateMany(where: PostWhere, data: PostUpdateManyInput!): PostBatch postUpsert(where: PostWhereUnique!, create: PostCreateInput!, update: PostUpdateInput!): Post postDelete(where: PostWhereUnique!): Post postDeleteMany(where: PostWhere): PostBatch } type PostBatch { count: Int! nodes: [Post!]! }
  • Mutations return records: the created, updated or upserted node, the deleted node as it was. Batch mutations return count and, when selected, the affected nodes (the deleted ones as they were), read in the same statement with the client’s batch select.
  • createMany and updateMany take scalars only (<Model>CreateManyInput, <Model>UpdateManyInput), as in the client: nested writes go through create / update.
  • Mutation root fields are nullable, like queries: a failing one is null with its error.

Nested writes

Relations in <Model>CreateInput take create and connect; in <Model>UpdateInput also disconnect (a list on to-many, disconnect: true on to-one) and, on to-many, set:

mutation { userUpdate( where: { id: "u1" } data: { name: "Alice" _ops: { loginCount: { increment: 1 } } following: { connect: [{ email: "bob@acme.io", _edge: { since: "2026-11-01T00:00:00Z" } }] disconnect: [{ email: "carol@acme.io" }] } posts: { create: [{ title: "Hello", tags: { connect: [{ name: "graphs" }] } }] } } ) { name following { email _edge { since } } } }
  • connect is a MERGE: connecting a pair that is already linked keeps one edge and updates the _edge properties given (edge defaults are set only when the edge is created). On a to-one relation, connect (or create) replaces the edge; when the other side is to-one (connecting a post through user.posts while Post.author is User?), the post moves. Numeric _edge properties take _ops on connect / set: _edge: { _ops: { weight: { increment: 1 } } }.
  • set makes the listed nodes the only linked ones (edges to the others are deleted, the listed ones are kept or connected).
  • Inputs are generated per relation side: a nested create omits the back relation (UserCreateWithoutPostsInput has no posts), and its relation input is named after it (PostCreateManyWithoutAuthorRelation). Items of a typed edge take _edge; connect items are the target’s unique key plus _edge (UserConnectFollows).
  • A model whose create is off has no nested create either: with Tag read-only, PostCreateInput.tags has connect only. Nested update, delete, upsert and connectOrCreate are not served yet.
  • Unions take a member-keyed item ({ Post: { … } }); an interface is connected by its unique key, and created through its implementations.

Scalar updates

A field of <Model>UpdateInput takes the new value; null removes the property (a required field cannot be null: BAD_USER_INPUT). Numeric operators go in _ops, applied in order: _ops: { views: { increment: 1 }, score: { multiply: 2 } }. Setting a field and an _ops operator on it is a BAD_USER_INPUT error. @min / @max are checked on the value an operator produces.

Validation

Validation rules (@length, @min, @email, …) and enum values are checked before anything is written, as in the client. The error lists every broken rule in extensions.issues, with paths in GraphQL argument terms:

{ "message": "User.create: 1 value breaks the schema's validation rules: …", "extensions": { "code": "BAD_USER_INPUT", "issues": [ { "path": ["data", "posts", "create", 1, "title"], "model": "Post", "field": "title", "rule": "length", "message": "must be at least 3 characters long (got 2)." } ] } }

A rule broken by an _ops update has _ops in its path (["data", "_ops", "loginCount"]).

Transactions

Each mutation root field is its own transaction (by default), and the fields of one operation run in order. With mutationTransaction: "request", every root field of a mutation operation runs in one write transaction (one statement each, in order): they commit together or not at all. The first failing field rolls the whole operation back, the remaining fields are not run, and every root field is null with that field’s error (nothing it reported was committed).

Auth

Authorization is configured in graphql.config.ts, next to the operations it guards, as TypeScript functions of the request’s context. Rules are schema-level and compiled into the statement: the same where the client compiles is ANDed into every place the model is matched, so nothing is filtered in JavaScript and no query can read around a rule.

graphql.config.ts
import { defineGraphQL } from "@cyphra/graphql/native"; import type { CyphraTypeMap } from "./cyphra.gen"; type Ctx = { user?: { id: string; role: "MEMBER" | "ADMIN" } }; const me = (ctx: Ctx) => ctx.user?.id ?? ""; export const api = defineGraphQL<CyphraTypeMap, Ctx>({ models: { User: { operations: { update: ["update"] }, fields: { passwordHash: false, email: { read: { where: ({ ctx }) => ({ id: me(ctx) }) } }, // each user reads their own salary: { read: ({ ctx }) => ctx.user?.role === "ADMIN" }, // admins only }, rules: { update: ({ ctx }) => ({ id: me(ctx) }) }, }, Post: { operations: { create: true, update: true, delete: true }, authenticated: { create: true, update: true, delete: true }, rules: { read: ({ ctx }) => ({ OR: [{ published: true }, { author: { is: { id: me(ctx) } } }] }), update: ({ ctx }) => ({ author: { is: { id: me(ctx) } } }), delete: ({ ctx }) => ctx.user?.role === "ADMIN" ? true : { author: { is: { id: me(ctx) } } }, after: { create: ({ ctx }) => ({ author: { is: { id: me(ctx) } } }) }, connect: { tags: () => ({ internal: false }) }, }, }, AuditLog: { rules: { read: () => false } }, }, });

Authentication

makeSchema does not verify tokens: the server’s context function does, and Ctx types what rules see. native.jwtContext builds such a context from the Authorization: Bearer <jwt> header, with the same verifier as compat.v7’s features.authorization, so both APIs can share one context function:

app/api/graphql/route.ts
import { createYoga } from "graphql-yoga"; import { native } from "@cyphra/graphql"; const yoga = createYoga({ schema, context: native.context( schema, native.jwtContext({ key: process.env.JWT_SECRET!, // or { url: "https://…/.well-known/jwks.json" } verifyOptions: { issuer: "https://auth.example.com", audience: "api" }, user: (jwt) => ({ id: jwt.sub!, role: jwt.role as "MEMBER" | "ADMIN" }), }), ), });
  • The context is { token, jwt, user }: jwt is the verified payload, user what the user option makes of it. A missing, malformed, expired or forged token leaves the request anonymous (no jwt, no user), as in compat.v7. It reads { request } (GraphQL Yoga, Fetch servers) or { req } (Apollo Server on Node).
  • Any context function works: context: async ({ request }) => ({ user: await verify(request) }).
  • native.context(schema, build) (optional) also sets ctx.cyphra before any resolver runs.

authenticated

models.<M>.authenticated names the operations that need an authenticated request: true (all of them) or per group, like operations ({ create: true, update: ["update"] }). An anonymous request gets UNAUTHENTICATED before anything runs. A request is authenticated when config.isAuthenticated(ctx) says so (default: the context has a user or a jwt).

A whole group (read: true, create: true, …) also applies wherever the model is reached: for an anonymous request, the model’s nodes are not there in relations, _count and relation filters (read), and nested writes cannot create or update them. A list of operations guards only those root fields.

Rules

A rule is a function of { ctx } returning true (allowed), false (denied) or a where on the model, typed as the client’s where of that model:

RuleApplies to
readEvery read of the model: root fields, relation loads at any depth, relation filters (some / none / every / is), _count, totalCount, mutation results, and the targets of writes.
create({ ctx, data }) => boolean: each node created, root or nested, from its create data, before anything runs.
updateThe nodes update / updateMany / upsert match, whatever they write (scalars, relations only, or nothing).
deleteThe nodes delete / deleteMany match.
connect.<relation>The targets a nested connect / set may link (a where on the target model).
disconnect.<relation>The targets a nested disconnect / set may unlink.
after.create / .updateChecked on the nodes created / updated once every write of the statement ran (nested ones included); a node that does not match rolls the whole write back.
  • Compiled, not filtered in JavaScript. A where rule is the client’s where: relations, _on, _labels, anything a filter can do. Context values are parameters. A rule’s own where is not subject to other rules.
  • Evaluated once per request, against its context, and shared by its root fields.
  • Denied vs not found. An update / delete / connect on a node outside its rules fails with NOT_FOUND: the node does not exist for this request, so a rule never reveals that a key exists. A node the request cannot read cannot be updated, deleted, connected or disconnected either. false (the whole operation denied) fails the root field with FORBIDDEN; a failing create or after rule is FORBIDDEN too, and nothing is written.
  • Relationships. Connecting a node whose other side is to-one (user.posts.connect moves a post from its author) is an update of that node: its update rule applies. A to-one edge a write must replace (connect or create on post.author) is a disconnect of the current target: outside the disconnect rule, the write is FORBIDDEN. Explicit disconnect / set leave the edges outside the rule alone.
  • Mutation results apply read: relations of the written node show what the request can read, field rules apply, and a written node the request cannot read is returned as null (the write happened). Batch nodes leave such nodes out.
  • Interfaces and unions. A rule on an interface applies to every implementation; a node matched through an interface or a union gets its own model’s rules too.
  • Startup check. Rule keys, models and relations are typed from CyphraTypeMap, and makeSchema checks them again. It also calls every where rule once with an empty context ({ ctx: {} }) and checks the fields and relations of the where it returns, so { publishd: true } fails at startup even in JavaScript. A rule that throws without a context is checked on its first request (an invalid where then fails that request with INTERNAL_SERVER_ERROR).

TypeScript checks object literals returned by a function only partly: ({ publishd: true }) and ({ author: { is: { emial: "x" } } }) fail tsc, but a misspelled key next to a correct one (({ published: true, publishd: true })) does not. The startup check catches it.

On FalkorDB, which cannot roll a write back, after rules and disconnect rules are refused.

Field rules

fields.<f>.read takes a rule instead of a boolean. A field with a rule is generated nullable.

  • Context-only: read: ({ ctx }) => boolean, evaluated once per request. A denied field selected is null with a FORBIDDEN error at its path (extensions.field names it); using it in where, orderBy (also through a relation) or _count fails the root field with FORBIDDEN before anything runs.
  • Row-dependent: read: { where: ({ ctx }) => … }, compiled to CASE WHEN <where> THEN n.email END. The field is null on the rows the where does not match, and filters, ordering, unique lookups and mutation results see that null too: no query can probe the hidden values. Scalar fields only; not the @id field.

A rule on a field of an interface goes on the interface and applies to every implementation.

ctx.cyphra

ctx.cyphra is the request’s client with the API’s rules applied (the same rules as the generated root fields), for custom resolvers and anything else that reads on the request’s behalf; ctx.cyphra.$unsafe is the client without them, for the rare code that must.

const yoga = createYoga({ schema, context: native.context(schema, native.jwtContext({ key })) }); // In a resolver: const drafts = await ctx.cyphra.post.findMany({ where: { published: false } }); // only readable ones const all = await ctx.cyphra.$unsafe.post.count(); // no rules

native.context(schema, build) sets it before any resolver runs. Without it, the first generated root field of the request sets it, when the context has no cyphra of its own.

Hooks

Rules are declarative and reach every place a model appears in a statement. Query hooks (a client function: (ctx) => db.$extends(…)) are code around one root operation: they do not run for post loaded under user { posts }. Use a rule for anything that must hold wherever a model is reached, and hooks for the rest (hashing a password, audit logs, soft delete).

Security guide

Checklist for an API exposed to untrusted clients:

  1. Expose on purpose. Writes are off by default; turn on the operations each model needs, per group or per operation. Hide fields no client should see with fields: { f: false }.
  2. Guard data with rules, not with toggles. operations: { read: false } removes root fields only: the model is still reached through relations. rules: { read } hides its nodes everywhere.
  3. Write update / delete rules for every writable model, and after.create (or a create rule) to constrain what a create may produce, such as the author being the requester.
  4. Guard relationships. connect / disconnect rules restrict what nested writes may link; remember that connecting through a to-many side can move a node off its to-one owner (its update rule applies).
  5. Use field rules for sensitive values (emails, salaries): they cannot be filtered, sorted or looked up by unique key around the rule.
  6. Use ctx.cyphra in custom resolvers, so they apply the same rules; keep $unsafe for code that must bypass them, and review it.
  7. Set limits (maxDepth, maxTake, maxComplexity) to bound what one request may load, and leave debug off in production.
  8. Commit the printed contract (cyphra graphql print --check) so a change in what the API exposes shows up in review.

What the native API fixes over @neo4j/graphql v7 (each has a test in packages/graphql/test/native.auth.integration.test.ts and the auth fixture of the compat suite):

v7Native API
@mutation(operations: []) hides root mutations; a nested create through another type worksA model whose writes are off has no nested create; a create rule holds through nested writes.
@query(read: false) types are readable through relationshipsA read rule hides the nodes in relations, _count, relation filters and connects.
where / sort / aggregation filters can probe fields and nodes the user cannot readFilters and sorting only see readable nodes, and ruled fields as null (or FORBIDDEN).
AGGREGATE rules are separate from READ rulesOne read rule covers counts, totalCount and _count.
Relationship-only updates skip the node’s UPDATE rulesupdate restricts every update, whatever it writes; connects that move a node need its update.
create responses ignore READ rulesMutation results apply read and field rules.
Rules are strings in SDL directives, checked when the schema is builtRules are TypeScript, typed against schema.cyphra, and checked again at startup.

Scalars

CyphraGraphQL
String with @idID
String, Int, Float, Booleanthe same (Int is GraphQL’s 32-bit Int: use BigInt above it)
DateTimeDateTime (ISO 8601: 2026-11-01T09:30:00.000Z)
DateDate (yyyy-mm-dd)
LocalDateTime, LocalTime, Time, Durationthe same names, ISO 8601 strings
BigIntBigInt (a decimal string)
JsonJson (any JSON value)
Point, CartesianPointobjects ({ longitude latitude height }, { x y z }), PointInput
Vector(N)[Float!]
enuma GraphQL enum
@@labels([…])_labels: [String!]!, filtered with _labels: { has, hasSome, … }

Optional fields are nullable; required ones are non-null; lists are [T!]!.

Limits

config.limits bounds what one root field may ask the database to load. Each is checked before the statement is built; exceeding one fails the root field with BAD_USER_INPUT and extensions.limit naming it.

LimitDescription
maxDepthDeepest relation nesting (a root’s relations are depth 1).
maxTakeLargest take of a list, root or relation; also the take of a list that sets none.
maxAliasesMost aliased fields in one root field’s selection.
maxComplexityMost rows a root field may load: each list multiplies its parent’s rows by its take (maxTake, or 100, when it has none).

Errors

Errors carry a stable extensions.code, mapped from the client’s errors:

Errorextensions.codeextensions
CyphraValidationError (bad input, invalid cursor, no unique key)BAD_USER_INPUTissues (paths in GraphQL argument terms) when the client lists some
_edge outside its context, two keys in one orderBy elementBAD_USER_INPUT
a value and an _ops operator on one field, null for a required fieldBAD_USER_INPUT
a limit exceededBAD_USER_INPUTlimit
NotFoundError (update / delete / connect target missing)NOT_FOUND
RestrictErrorRESTRICTEDmodel, relation, target, count
UniqueConstraintError (a duplicate @id / @unique value)UNIQUE_CONSTRAINTmodel, fields, constraint (never the value)
authenticated and an anonymous requestUNAUTHENTICATEDmodel, operation
a rule denying the whole operation (false)FORBIDDENmodel, operation
a create rule, an after rule, a to-one replace outside disconnectFORBIDDENmodel, operation (relation)
a field a context-only rule denies (selected, filtered, sorted)FORBIDDENmodel, field
anything else (driver, bug)INTERNAL_SERVER_ERRORmessage masked unless debug: true

Relay

relay: true in the config adds Relay’s Node interface and a node(id: ID!) root field:

interface Node { id: ID! } type Post implements Node { id: ID! # the global id rawId: ID! # the post's own id field title: String! } type Query { node(id: ID!): Node }
  • Every model with an @id field of type String, Int or BigInt implements Node (an interface with one implements it too). Its global id is base64("<Type>:<id>"); native.toGlobalId / native.fromGlobalId build and read them on the server.
  • The model’s own field named id is returned as rawId, since id is the global id. Inputs (where, orderBy, <model>FindUnique) keep id with raw values. A model with a field already named rawId is a makeSchema error.
  • node(id) is one findUnique. It returns null for an id of an unknown type, of a model whose reads are all off, or of a node that does not exist; a string that is not a global id is a BAD_USER_INPUT error.

Relay is off by default.

The generated SDL is deterministic: printed with lexicographicSortSchema and printSchema, descriptions included. Commit it and check it in CI, so a field removed by a schema edit or a config toggle shows up in review:

cyphra graphql print --out schema.graphql # write it (reads graphql.config.ts) cyphra graphql print --check # fails when schema.graphql is out of date

--check lists the breaking and dangerous changes between the committed SDL and the generated one (CLI reference). From code, native.printSchema(schemaModel, config) returns the same text. config.generator pins the generator version: a release that would print something else for the same schema and config ships it as a new, opt-in version.

One statement per root field

A root field’s arguments and its whole selection (fragments resolved, @skip / @include applied, variables substituted) are translated into one client operation, which compiles one Cypher statement (COLLECT {} / COUNT {} subqueries for relations, CASE WHEN n:Label for fragments). Nested fields do no I/O: a query runs as many statements as it has root fields, whatever its depth. A findMany that selects totalCount with its nodes runs the page and the count in one read transaction. A mutation root field (nested writes and the returned record included) is one write statement too.

Side by side with compat.v7

The two APIs have types with the same names and different shapes, so they are served on separate endpoints, from the same client or driver and the same graph:

app/api/graphql/[[...v]]/route.ts
const v7 = compat.v7.makeSchema({ typeDefs, client: db.$client }); const v2 = native.makeSchema({ client: db, config: api }); // /api/graphql stays the v7 API; /api/graphql/v2 is the native one.

Frontends move operation by operation: movies(where, sort, limit) becomes movieFindMany(where, orderBy, take) { nodes }, actorsConnection { edges { properties } } becomes actors { _edge { … } }, { eq: … } becomes { equals: … }. Keyset cursors are not interchangeable with v7’s offset cursors. The migration guide covers moving the type definitions to schema.cyphra (cyphra import graphql).

Last updated on