Skip to Content
GraphQLcompat.v7

GraphQL

@cyphra/graphql serves the API that @neo4j/graphql 7.6 generates from your type definitions: the same types, fields, filters, sorting, pagination and results. You keep your typeDefs and your frontend queries, and the API runs on the Cyphra runtime.

This is an early release. The full v7 schema is generated, and queries (aggregations included), mutations, @authentication / @authorization rules, @cypher fields, @fulltext queries, unions, interfaces and subscriptions work. Some scalars are not supported yet. See what works today.

The native API (native.makeSchema, experimental) serves an API generated from schema.cyphra instead, with the typed client’s semantics. Both can be served side by side.

Install

npm i @cyphra/graphql graphql neo4j-driver

It needs Neo4j 5.23 or later (like @neo4j/graphql 7) and graphql 16.

Create the schema

compat.v7.makeSchema takes the type definitions you pass to new Neo4jGraphQL(...) and returns a GraphQLSchema with its resolvers. Any GraphQL server can serve it.

lib/graphql.ts
import { compat } from "@cyphra/graphql"; import neo4j from "neo4j-driver"; import { typeDefs } from "./typeDefs"; const driver = neo4j.driver( process.env.NEO4J_URI!, neo4j.auth.basic(process.env.NEO4J_USERNAME!, process.env.NEO4J_PASSWORD!), ); // Before: await new Neo4jGraphQL({ typeDefs, driver }).getSchema() export const schema = compat.v7.makeSchema({ typeDefs, driver });
OptionDescription
typeDefsYour v7 type definitions (@node, @relationship, …), as a string.
driverA neo4j-driver driver.
clientA CyphraClient, instead of driver, to share the connection of your app.
databaseDatabase name used with driver. Default: the default database. A request’s context.sessionConfig.database takes precedence.
debugLog each generated Cypher statement and its parameter names (not values).
features{ authorization }: how JWTs are verified, as in v7 (below).

makeSchema throws an UnsupportedTypeDefsError when the type definitions use something it cannot serve yet (Point, Duration, custom scalars, …). It never serves an API that differs from v7 without telling you: a directive or argument it does not implement is rejected, never ignored.

The error lists every issue at once, not only the first one: its issues hold a code (UNSUPPORTED for what @cyphra/graphql does not serve yet, INVALID for type definitions v7 rejects too, with v7’s message), the message and a location (type, field, line, column). UnsupportedTypeDefsError extends CyphraError. To evaluate a migration from @neo4j/graphql without building the schema, get the same list with checkTypeDefs, or run cyphra graphql check on your .graphql files:

import { compat } from "@cyphra/graphql"; for (const issue of compat.v7.checkTypeDefs(typeDefs)) { console.log(`${issue.location.line}:${issue.location.column} ${issue.code} ${issue.message}`); }

checkTypeDefs also takes several files, [{ name, body }], checked together: each issue’s location.source is then its file.

As in v7, a request’s context.sessionConfig (database, impersonatedUser, auth) is spread over the session options of every statement of the request, so one schema can serve several databases or run as the signed-in user. Its database wins over the database option. It needs driver: with client, a request that sets sessionConfig fails with an error instead of running on the client’s database.

const yoga = createYoga({ schema, // tenantDatabase: your own lookup, e.g. from the request's host or token. context: ({ request }) => ({ sessionConfig: { database: tenantDatabase(request) } }), });

printSchema(schema) prints the schema exactly as v7 does, byte for byte: types, fields, arguments, input fields and enum values come in v7’s order (moviesConnection before movies, movies(where, limit, offset, sort), moviesConnection(first, after, where, sort), your own types and fields where v7 puts them). If you commit the printed schema as a contract and diff it in CI, switching from new Neo4jGraphQL(...) leaves that file unchanged.

Serve it from a Next.js route

With GraphQL Yoga:

app/api/graphql/route.ts
import { createYoga } from "graphql-yoga"; import { schema } from "@/lib/graphql"; const { handleRequest } = createYoga({ schema, graphqlEndpoint: "/api/graphql", fetchAPI: { Response }, }); export { handleRequest as GET, handleRequest as POST, handleRequest as OPTIONS };

With Apollo Server:

app/api/graphql/route.ts
import { ApolloServer } from "@apollo/server"; import { startServerAndCreateNextHandler } from "@as-integrations/next"; import type { NextRequest } from "next/server"; import { schema } from "@/lib/graphql"; const server = new ApolloServer({ schema }); const handler = startServerAndCreateNextHandler<NextRequest>(server); export { handler as GET, handler as POST };

Queries written for @neo4j/graphql work as they are:

query { movies( where: { actors: { some: { name: { eq: "Keanu Reeves" } } } } sort: [{ released: DESC }] ) { title actorsConnection(first: 2, sort: [{ edge: { screenTime: DESC } }]) { totalCount edges { cursor properties { roles } node { name } } pageInfo { hasNextPage endCursor } } } }

Mutations written for @neo4j/graphql work as they are too, nested writes included:

mutation { updateMovies( where: { title: { eq: "The Matrix" } } update: { released: { add: 1 } actors: [ { connect: [{ where: { node: { name: { eq: "Al Pacino" } } }, edge: { roles: ["Cameo"] } }] } { disconnect: [{ where: { node: { name: { eq: "Laurence Fishburne" } } } }] } ] } ) { info { relationshipsCreated relationshipsDeleted } movies { title released } } }

Each root field runs as one Cypher statement, in its own transaction (a read transaction for queries, a write transaction for mutations). Values are always parameters, and labels, property keys and relationship types come from your type definitions.

compat.v7 runs on the same engine as the typed client and the native API when that engine answers exactly like v7: list and connection queries with their filters, sorting, paging and nested relationships, create with attribute inputs, update with set, and delete without nested deletes, on types without @authentication / @authorization. The rest (aggregations, full-text, @cypher, rules, unions, interfaces, nested writes, edge filters and sorts, single, arithmetic operators, …) runs on the compat compiler, with the same results. What you can see of the difference:

  • With client, the client’s query events and spans name the engine operation and model (findMany on Movie) instead of graphql.read / graphql.write.
  • A root connection that selects both a page (edges / pageInfo) and totalCount reads them with two statements in one read transaction.

Authentication and authorization

@authentication, @authorization, @jwt and @jwtClaim work as in v7, with the same results. The rules are compiled into the Cypher statement of each root field: filter rules are part of its WHERE, and validate rules are checked inside it. A node that the rules do not allow is never returned by the database, and a write that fails a rule is rolled back with the rest of the statement. JWT claims and context values are always passed as parameters. APOC is not needed.

Pass the JWT

Configure the key like features.authorization in v7, and pass the Authorization header as token in the GraphQL context:

lib/graphql.ts
export const schema = compat.v7.makeSchema({ typeDefs, driver, features: { authorization: { key: process.env.JWT_SECRET! } }, });
app/api/graphql/route.ts
const { handleRequest } = createYoga({ schema, graphqlEndpoint: "/api/graphql", fetchAPI: { Response }, context: ({ request }) => ({ token: request.headers.get("authorization") ?? undefined }), });
features.authorizationDescription
keyA secret (HS256, HS384, HS512), { url } of a JWKS endpoint (keys are cached), or a function of the context that returns one of the two.
verifyOptionsPassed to jwtVerify of jose: issuer, audience, algorithms, clockTolerance, …
verifyfalse decodes the token without checking its signature. Only for tokens already verified upstream: anyone can forge an unverified token.

The context keys are the ones v7 reads:

  • token: Bearer <jwt> (or the bare JWT). A missing, malformed, expired or forged token leaves the request unauthenticated, without an error, as in v7.
  • jwt: a payload your server already verified. It is trusted as it is and takes precedence over token.
  • Any other key can be read by a rule as $context.<path>, for example $context.tenant.id.

Rules

Everything v7 accepts is supported:

  • @authentication(operations, jwt) on a type, on a field, or for every type with extend schema @authentication(…). It fails with Unauthenticated before anything runs.
  • @authorization(filter: [...], validate: [...]) on a type or a field, with operations (READ, AGGREGATE, CREATE, UPDATE, DELETE, CREATE_RELATIONSHIP, DELETE_RELATIONSHIP), requireAuthentication and, for validate, when: [BEFORE, AFTER]. A failed validate rule fails the root field with Forbidden.
  • where: { node: …, jwt: … } with AND / OR / NOT, any filter of the type in node (relationships included), and "$jwt.<claim>" / "$context.<path>" values.
  • The rules of related types apply to nested selections, connections and nested writes.
type JWT @jwt { roles: [String!]! @jwtClaim(path: "app.roles") } type Post @node @authorization( filter: [ { operations: [READ] where: { OR: [ { node: { published: { eq: true } } } { node: { author: { single: { id: { eq: "$jwt.sub" } } } } } ] } } ] validate: [ { operations: [UPDATE, DELETE] when: [BEFORE] where: { OR: [ { node: { author: { single: { id: { eq: "$jwt.sub" } } } } } { jwt: { roles: { includes: "admin" } } } ] } } ] ) { id: ID! @id title: String! published: Boolean! author: [User!]! @relationship(type: "WROTE", direction: IN) }

v7 authorization behaviour you get as well

These come from v7 and are kept so results do not change. Some of them matter for security:

  • Rules require authentication by default (requireAuthentication: true): an anonymous request reads nothing from a type with a filter rule, and fails its validate rules.
  • Rules only cover what is selected or written. where filters, sort and aggregation filters can use fields and relationships the user cannot read: users(where: { documents: { some: … } }) tells which users own a matching document, even a hidden one, and filtering or sorting on a field with a field-level rule is not checked. Keep data that must not be probed behind a type-level rule of the type that holds it.
  • A connection aggregate uses the AGGREGATE rules, not the READ ones: give AGGREGATE the same filter as READ unless counts may differ.
  • An update that only writes relationships of a node (connect, disconnect, …) does not apply that node’s UPDATE rules; the rules of the related type and the relationship rules (CREATE_RELATIONSHIP, DELETE_RELATIONSHIP) still apply.
  • The response of a create mutation returns the created nodes without their READ rules (nested selections apply them). The response of an update applies them.
  • CREATE rules are checked after the write (validate with when: [AFTER]), there are no filter rules for CREATE. On connect, the source node is only checked after the relationship is created.
  • A jwt passed in the context is trusted, and @jwtClaim paths only apply to tokens verified from token, not to it.

Differences from v7

@cyphra/graphql is stricter than v7 in a few cases, where v7 is more permissive than its rules read or fails with an internal error:

  • Inside an AND / OR element, node and jwt must both hold. v7 combines them with the element’s operator, so OR: [{ node: …, jwt: … }] passes when either holds.
  • NOT works at the top of a rule (v7 throws).
  • A validate rule that evaluates to null (a compared property is missing) fails with Forbidden. v7 fails with an APOC error.
  • A $context value that is not in the context is null, so the comparison matches nothing. v7 fails with a Neo4j “Expected parameter” error.
  • In @authentication(jwt: …), eq does not consider a list equal to a string.
  • A rule that does not fit its type (unknown field, wrong operator) makes makeSchema throw, and @authentication / @authorization on relationship fields or relationship properties is rejected instead of ignored.

Custom Cypher fields

@cypher(statement, columnName) works as in v7 on fields of node types, on relationship properties and on Query / Mutation fields. The statement runs inside the root field’s statement, so a query with @cypher fields is still one Cypher statement.

type Movie @node { title: String! actors: [Person!]! @relationship(type: "ACTED_IN", direction: IN) actorCount: Int! @cypher(statement: "MATCH (this)<-[:ACTED_IN]-(a:Person) RETURN count(a) AS n", columnName: "n") similar(limit: Int = 3): [Movie!]! @cypher( statement: """ MATCH (this)<-[:ACTED_IN]-(:Person)-[:ACTED_IN]->(m:Movie) WHERE m <> this RETURN DISTINCT m LIMIT $limit """ columnName: "m" ) } type Query { moviesSince(year: Int!): [Movie!]! @cypher(statement: "MATCH (m:Movie) WHERE m.released >= $year RETURN m", columnName: "m") }
  • this is the node (or the relationship, on relationship properties) the field belongs to.
  • $name refers to an argument of the field. Each value is passed as a parameter, never written into the statement: a missing or null argument becomes NULL, and default values apply.
  • $jwt is the JWT of the request ({} when it is not authenticated), and the keys of context.cypherParams are passed as parameters too.
  • Scalar @cypher fields without arguments can be used in where and sort, like v7 generates them. Fields that return nodes can be filtered with some / all / none / single (lists) or with a node filter (one node).
  • Nodes returned by a statement get the READ rules of their type, and the selection works as for any node: nested relationships, connections and other @cypher fields.
  • Query fields run in a read transaction, Mutation fields in a write transaction. Their @authentication (on the field or on type Query / type Mutation) is checked first.

As in v7:

  • A scalar field takes the columnName value of each row. When the statement returns no row, the node is left out of the result; when it returns several rows, the node appears once per row. A list field collects the values of every row, and list values are flattened.
  • A Query or Mutation field that is not a list returns the first row, or null.
  • all on a list of nodes is true when the statement returns no node.

Custom resolvers

Pass your resolvers as resolvers, as you would to new Neo4jGraphQL({ typeDefs, resolvers }). They are merged with the generated ones (an array is merged in order) and serve:

  • Query and Mutation fields without @cypher;
  • object, input, enum and union types without @node, which are added to the schema as written;
  • @customResolver fields of @node types, and their fields that return a type without @node;
  • any generated field you want to replace.
type Lab @node { id: ID! title: String! myProgress: Progress @customResolver(requires: "id") } type Progress { labId: ID! percent: Int! } type Query { stats: Stats! }
const schema = compat.v7.makeSchema({ typeDefs, driver, features: { authorization: { key: process.env.JWT_SECRET! } }, resolvers: { Lab: { // `lab` always has `id` (the `requires` selection), even when the query does not select it. myProgress: (lab, _args, context) => loadProgress(context.jwt?.sub, lab.id), }, Query: { stats: async (_root, _args, context) => { const { records } = await context.executionContext.executeQuery( "MATCH (l:Lab) RETURN count(l) AS n", ); return { labCount: records[0].get("n") }; }, }, }, });

As in v7:

  • A @customResolver field is left out of the generated Cypher and of every where, sort, create and update input. The requires selection (fields, relationships and connections of the type) is always fetched, and the resolver is called with the parent object.
  • Before a Query or Mutation resolver runs, context.jwt is set to the payload of the verified context.token (unless you passed jwt) and context.executionContext to the driver (unless you passed one), so your resolvers, nested ones included, can read them.
  • @authentication on type Query / type Mutation, on extend schema or on the field applies to fields served by your resolvers.
  • makeSchema throws "X" defined in resolvers, but not in schema for a resolver of an unknown type or field, and warns when a @customResolver field has no resolver.
  • Int, Float and ID fields convert Neo4j integers your resolvers return.

Differences from v7:

  • @authentication applies to every Query / Mutation field served by your resolvers. v7 7.6.8 applies it to the first two only: the glob it builds to select them keeps a space before the third name.
  • Fields served by resolvers can use the scalars, enums, @node types, unions and types without @node of the type definitions, not generated types such as LabWhere. Resolvers for scalar or enum types (internal enum values) and type Subscription fields are not supported yet.

@fulltext generates the v7 full-text query fields, which call db.index.fulltext.queryNodes:

type Movie @node @fulltext(indexes: [{ indexName: "MovieTitle", queryName: "moviesByTitle", fields: ["title"] }]) { title: String! released: Int }
query { moviesByTitle( phrase: "matrix" where: { score: { min: 0.5 }, node: { released: { gt: 1990 } } } sort: [{ score: DESC }] first: 10 ) { totalCount edges { score node { title } } pageInfo { hasNextPage endCursor } } }

phrase uses the Lucene query syntax of Neo4j full-text indexes. Results are filtered by where (score and node) and the READ rules of the type, sorted by sort (the index order, best score first, without it) and paginated with first / after.

Like v7, @cyphra/graphql does not create the index: create it before you query it. With Cyphra migrations, declare it in schema.cyphra with @@fulltext and the same name (@@fulltext([title], name: "MovieTitle")), and cyphra migrate creates it; or run CREATE FULLTEXT INDEX MovieTitle IF NOT EXISTS FOR (n:Movie) ON EACH [n.title] yourself. Wait for a new index to be ONLINE (CALL db.awaitIndexes()) before relying on its results. A query on a missing index fails with the Neo4j error.

Unions

A union of @node types (union Content = Movie | Book) gets the v7 API: the root query contents(where, limit, offset), relationship fields to the union (favorites(where, limit, offset) and favoritesConnection(where, sort, first, after), edge properties included) and nested writes keyed by member. A union adds no label, like in v7: a Content is a Movie or a Book node.

query { users { favorites(where: { Movie: { year: { gt: 2000 } } }) { __typename ... on Movie { title } ... on Book { isbn } } } } mutation { updateUsers( where: { name: { eq: "ana" } } update: { favorites: { Movie: [{ connect: [{ where: { node: { title: { eq: "Up" } } }, edge: { rating: 4 } }] }] Book: [{ disconnect: [{ where: { node: { isbn: { eq: "b-1" } } } }] }] } } ) { info { relationshipsCreated relationshipsDeleted } } }

What v7 does, and @cyphra/graphql too:

  • A union where selects members: { Movie: { … } } returns movies only, { Book: {} } every book, and {} (or no where) every member. Each member gets its own READ rules.
  • limit and offset apply to the rows of all members together, in no particular order: there is no sort on a union list. A connection sorts on edge properties only (sort: [{ edge: … }]), and has no aggregate. limit: 0 is ignored.
  • A node reached twice (two relationships to the same node) is returned once in a list, and a connection keeps one edge per node and selected properties: totalCount counts those edges.
  • Relationship filters test each member named in the filter: some is true when one of them matches, all and none must hold for every member named, and single combines the members with XOR (with two members: one of them has exactly one match, the other does not). A member without conditions (favorites: { none: { Book: {} } }) tests that there is no book for none and that there is one for some.
  • Nested create, connect, update, disconnect and delete take one input per member (favorites: { Movie: […], Book: […] }), with the member’s where and the edge properties.

One difference: v7 7.6.8 ignores where and edge when a union field is connected or disconnected inside another connect / disconnect (fans: { connect: [{ where, connect: { favorites: { Book: [{ where }] } } }] }): it connects every node of every member, or deletes every relationship of the field. @cyphra/graphql applies where and edge there too. These are two of the three checks of the compatibility suite that differ on purpose. @cypher fields returning a union are not supported yet.

Interfaces

An interface implemented by @node types gets the v7 API: the root queries learningActivities(where, sort, limit, offset) and learningActivitiesConnection (with aggregate), relationships to the interface, relationship fields declared on the interface with @declareRelationship, and nested writes through them.

interface LearningActivity { id: ID! title: String! durationMinutes: Int tracks: [Track!]! @declareRelationship } type Lab implements LearningActivity @node(labels: ["Lab", "LearningActivity"]) { id: ID! @id title: String! durationMinutes: Int image: String tracks: [Track!]! @relationship(type: "CONTAINS", direction: IN, properties: "ContainsProperties") } type Track @node { id: ID! @id name: String! contains: [LearningActivity!]! @relationship(type: "CONTAINS", direction: OUT, properties: "ContainsProperties") }
  • Like v7, an interface adds no label. A node is a LearningActivity when it has every label of one implementation: Lab nodes need both Lab and LearningActivity here. Give the implementations a shared label in @node(labels) to find them all with one label in Cypher.
  • where takes the interface fields, the declared relationships and typename: [Lab, Quiz] (the implementations to keep; [] keeps all). sort, limit, offset, cursors and aggregate apply across implementations. An implementation can store a field under another property (@alias) or declare a relationship with another type or direction: each is read and filtered with its own.
  • Results come back with their implementation type: select its fields with fragments (... on Lab { image }).
  • @authorization goes on the implementations (v7 rejects it on interfaces): reading through the interface applies each implementation’s rules to its nodes. @authentication of every implementation applies to reads through the interface.
  • Writes go to implementations. create through a relationship to the interface is keyed by implementation (node: { Lab: { title: "…" } }); connect, update, disconnect and delete apply the interface where (with typename) to the nodes of each implementation.
  • A relationship an interface declares uses the interface’s connection types on every implementation (Lab.tracksConnection: LearningActivityTracksConnection!, without aggregate). Its connection where and sort, and edge inputs written through the interface, key edge properties by properties type (edge: { ContainsProperties: { position: { eq: 1 } } }), and properties is a union of the properties types: read it with ... on ContainsProperties.
  • @query, @plural and @limit work on interfaces, and @selectable, @settable, @filterable, @sortable on their fields (they shape the interface types, not the implementations).

Some v7 7.6.8 queries on interfaces fail with an internal error, and @cyphra/graphql serves them: aggregate on the root interface connection when an implementation has @authorization rules, count { edges } in the aggregate of a connection to an interface, typename inside a nested filter (contains: { some: { typename: [Lab] } }), keyed edge filters in aggregation filters through an interface, and keyed edge inputs when implementations use different properties types. after on the root interface connection skips one node more than the cursor in v7; here it continues right after the cursor, like for node types. A node with the labels of two implementations is returned once (as the first implementation in definition order), not once per implementation.

Not supported yet (makeSchema throws UnsupportedTypeDefsError): interfaces implementing interfaces, @declareRelationship to a union or with arguments, implementations without @node, an implementation narrowing a declared relationship to another type, interface fields implemented by @cypher fields, and @cypher fields returning interfaces.

Subscriptions

@subscription types get the v7 Subscription fields: movieCreated, movieUpdated and movieDeleted, with a where argument on the node’s properties. Events come from Neo4j Change Data Capture  (CDC), as with v7’s Neo4jGraphQLSubscriptionsCDCEngine: they include writes made outside the GraphQL API.

type Movie @node @subscription { title: String! released: Int } type Review @node @subscription(events: [CREATED, DELETED]) @subscriptionsAuthorization(filter: [{ where: { node: { author: { eq: "$jwt.sub" } } } }]) { author: String! body: String }
subscription { movieUpdated(where: { released: { gte: 2000 } }) { event timestamp previousState { title } updatedMovie { title } } }

Enable them

CDC needs Neo4j Enterprise Edition or Aura, with the database in CDC mode:

ALTER DATABASE neo4j SET OPTION txLogEnrichment 'FULL'

Then turn on features.subscriptions:

lib/graphql.ts
import { CDCSubscriptionsEngine, compat } from "@cyphra/graphql"; // `pollTime`: milliseconds between two reads of the change log (default 1000). export const engine = new CDCSubscriptionsEngine({ driver, pollTime: 500 }); export const schema = compat.v7.makeSchema({ typeDefs, driver, features: { authorization: { key: process.env.JWT_SECRET! }, subscriptions: engine }, }); // On shutdown: stops polling and ends the open subscriptions. process.on("SIGTERM", () => engine.close());

subscriptions: true creates the engine from driver (or client) with the defaults, and subscriptions: { pollTime, onlyGraphQLEvents } sets its options. With driver, the v7 name works too: new compat.v7.Neo4jGraphQLSubscriptionsCDCEngine({ driver, pollTime }). onlyGraphQLEvents: true keeps only the changes made by @cyphra/graphql mutations (it needs driver: they are recognized by their transaction metadata).

The engine reads the change log only while at least one subscription is open, and starts from the current position when the first one opens. On Neo4j Community, Memgraph, FalkorDB or a database without CDC, subscribing fails with an error that says so (GraphQL subscriptions need Neo4j Change Data Capture (CDC) …); with a client whose dialect is not neo4j, makeSchema throws.

Transports

The schema works with any server that supports GraphQL subscriptions.

graphql-ws (WebSocket), what v7 documents:

server.ts
import { createServer } from "node:http"; import { WebSocketServer } from "ws"; import { useServer } from "graphql-ws/use/ws"; import { createYoga } from "graphql-yoga"; import { schema } from "./lib/graphql"; const yoga = createYoga({ schema }); const server = createServer(yoga); const wsServer = new WebSocketServer({ server, path: yoga.graphqlEndpoint }); useServer( { schema, // The client connects with connectionParams: { token: "Bearer <jwt>" }. context: (ctx) => ({ connectionParams: ctx.connectionParams }), }, wsServer, ); server.listen(4000);

Server-sent events with GraphQL Yoga: Yoga serves subscriptions over SSE without extra setup (Accept: text/event-stream). Pass the Authorization header as token:

const yoga = createYoga({ schema, context: ({ request }) => ({ token: request.headers.get("authorization") ?? undefined }), });

A subscription reads its JWT from context.jwt (trusted, as for queries), then context.connectionParams.token (what v7 reads), then context.token.

Hosting

A subscription is a long-lived connection, and the engine polls the database in the background. Run the server as a long-running process: a Node.js server, a container, a VM, or a platform with WebSocket or streaming support. Serverless functions (Vercel functions, AWS Lambda behind API Gateway, …) are not a fit: they stop after the response or a time limit, close the connection and the polling with it. Keep queries and mutations on Vercel if you like, and serve the Subscription endpoint from a separate long-running service on the same database.

Each process runs its own engine: with several replicas, each one reads the change log. Changes are kept by Neo4j for the transaction log retention period, and a subscriber that reconnects gets the events from the moment it reconnects, not the ones it missed.

As in v7

  • Only node changes are published. Relationship changes are not (v7 7.x has no relationship events), and a node is published only when its labels are exactly the labels of a @node type.
  • @subscription(events: [...]) on a type, or extend schema @subscription(...) for every type, chooses the fields. Without either, there is no Subscription type.
  • where filters created events on the new properties, updated and deleted events on the previous ones. It has no relationship or @cypher filters. @cypher fields are in the payload and are null.
  • @subscriptionsAuthorization(filter) decides which events a subscriber receives: an event is delivered when no rule applies to its kind, or one of the rules that apply holds. Rules require an authenticated subscriber unless requireAuthentication: false. @authorization does not filter events (v7 prints a warning; so does Cyphra). On a field, @subscriptionsAuthorization has no effect.
  • @authentication(operations: [SUBSCRIBE]) checks the subscriber when it subscribes, and selecting the payload checks READ @authentication of the type and of the selected fields.
  • Updates that change nothing are not published.

Differences from v7

  • A filter on a property whose value is 0, false or "" matches: v7 skips falsy values, so available: { eq: false } never matches there. A missing property still never matches.
  • List equality (tags: { eq: ["a", "b"] }) compares the elements; v7 compares references and never matches. BigInt, Date and DateTime compare by value.
  • @alias fields are read from their property; v7 reads the field name.
  • A subscription can also authenticate with context.token (useful over SSE); close() ends the open subscriptions, and the engine only polls while one is open.

Schema configuration

The v7 schema configuration directives work as in v7: same generated schema, same behaviour.

DirectiveWhereEffect
@mutation(operations: [CREATE, UPDATE, DELETE])type, or extend schemaOnly the listed root mutations (createUsers, …) exist. [] removes all three; without root mutation left, there is no Mutation type.
@query(read: true, connection: <read>, aggregate: false)type, union, or extend schemaread: the root list query (users). connection: edges / totalCount / pageInfo of usersConnection. aggregate: its aggregate field.
@selectable(onRead: true, onAggregate: false)field, relationship, relationship propertyonRead: the field is in the object type and in subscription payloads. onAggregate: the field is in aggregate selections.
@settable(onCreate: true, onUpdate: true)field, relationship, relationship propertyThe field is in the create / update inputs (root and nested).
@filterable(byValue: true, byAggregate: false)field, relationship, relationship propertybyValue: the field is in where inputs. byAggregate: it is in aggregation filters.
@sortable(byValue: true)fieldThe field is in sort inputs. A type with no sortable field has no sort argument at all.
@limit(default, max)typePage size of every read of the type when no limit / first is given (default, else max), and its upper bound (max).

v7 details you get as well:

  • The defaults apply once a directive is written: @query alone turns aggregate off, @selectable alone turns onAggregate off and @filterable alone turns aggregation filters off.
  • @query / @mutation go either on the schema or on types, not both (makeSchema throws, like v7). @query(read: false) on a type also removes its connection, unless connection: true.
  • A list relationship with @selectable(onRead: false) keeps its …Connection field with only aggregate. On to-one relationships, @filterable has no effect (v7 always generates their filters). @sortable has no effect on relationship properties: v7 lists every property in the edge sort input.
  • A type with nothing settable gets _emptyInput: Boolean in its create / update input.
  • A root field hidden by @query / @mutation can be defined in type Query / type Mutation and served by your resolvers, e.g. a createUsers that sets the role on the server. Only the generated fields get the generated resolvers.
  • @selectable(onRead: false) also hides a field returning a type without @node. It cannot be combined with @customResolver, nor can the other configuration directives (makeSchema throws, like v7).
  • @limit applies to root and nested lists and connections, @cypher fields returning a list of the type, full-text queries and the nodes returned by create / update mutations. It does not apply to union queries or aggregate. With @limit, pageInfo.hasNextPage is computed from the requested first (it is false when first is not given), like v7.

These directives shape the API; they are not access control. As in v7:

  • @mutation(operations: []) removes createUsers, updateUsers and deleteUsers, but a user can still be created, updated, connected or deleted through the nested inputs of another type (createPosts(input: [{ author: { create: { node: { … } } } }])). Use @authorization(validate: [{ operations: [CREATE, …] }]) or @authentication(operations: [CREATE, …]) on the type, or @settable(onCreate: false, onUpdate: false) on the relationship fields that reach it.
  • @query(read: false) removes the root queries only: the type stays readable through relationships and in mutation responses. Use @authorization(filter) for data users must not see.
  • A field with @selectable(onRead: false) can still be filtered and sorted on, which reveals its value. Add @filterable(byValue: false, byAggregate: false) @sortable(byValue: false) or an @authorization rule on the field.

Never remove these directives to get past an UnsupportedTypeDefsError: the API would expose what v7 hides.

Differences from v7, on purpose:

  • With @limit, limit: 0 / first: 0 counts as “not given” (the default, capped by max). v7 ignores 0 after applying @limit and returns every node, which bypasses max. This is the one check of the compatibility suite that differs for @limit.
  • @selectable(onRead: false) on a to-one relationship is rejected: v7 generates a connection type without fields for it, which makes the whole schema invalid.
  • Every argument is checked: an unknown argument, a null where v7 expects a Boolean, an invalid @limit or an unknown @mutation operation make makeSchema throw.

What works today

Compatibility is checked by a suite of 20 apps and 288 operations. Its expected results come from the real @neo4j/graphql 7.6.8. Today 305 of its 308 checks pass: the printed schema of the 20 apps and 285 operations (queries, aggregations, mutations, authorization, @cypher fields, custom resolvers, full-text queries, unions, interfaces, to-one relationships, schema configuration directives, and subscription events on Neo4j Enterprise with CDC). The three others differ on purpose: the nested union connect / disconnect where v7 ignores where (unions), and limit: 0 on a type with @limit (schema configuration). The full report is compat/graphql/REPORT.md.

FeatureStatus
Generated schema: queries, connections, every where / sort / mutation input, aggregate types, deprecated field_OPERATOR fieldsWorks: the printed SDL is identical to v7, in its order
List queries: movies(where, sort, limit, offset), pluralization like v7, @pluralWorks
Filters on String, ID, Int, Float, BigInt, Boolean, Date, DateTime, enums and lists, with AND / OR / NOTWorks
Relationship filters some / all / none / single, connection filters on node and edgeWorks
Connections: totalCount, pageInfo, cursors with first / after, nested connections with edge properties, sort and filter on edgesWorks
Nested relationship fields with where, sort, limit, offsetWorks
To-one relationships (lab: Lab @relationship(…)): field, connection, where, nested create / delete, authorization rules through themWorks (details)
Aggregations: aggregate { count, node, edge } on root and nested connections, aggregation filters (aggregate and deprecated xAggregate)Works
Mutations: create, update, delete with info counters, and the response selectionWorks
Nested writes: create, connect, disconnect, update, delete (nested in each other), edge propertiesWorks
Update operators: set, add, subtract, multiply, divide, push, pop and the deprecated field_SET / field_INCREMENT / …Works
@id, @timestamp, @defaultWorks
@authentication / @authorization (type, field and schema level), @jwt, @jwtClaim, JWT verification (secret or JWKS)Works (details)
@cypher fields: scalars and nodes, arguments, $jwt, where and sort, relationship properties, Query and Mutation fieldsWorks (details)
@fulltext queries: score, where, sort, first / afterWorks (details)
Unions: root query, relationships to unions with edge properties, member-keyed where and nested writes. cyphra import graphql maps them to Cyphra unionsWorks (details)
Interfaces: root queries and connections, typename filters, relationships to interfaces, @declareRelationship, nested writes, per-implementation @authorizationWorks (details)
Subscriptions on CDC: @subscription, @subscriptionsAuthorization, where, @authentication(SUBSCRIBE) (Neo4j Enterprise / Aura)Works (details)
Custom resolvers: the resolvers option, Query / Mutation fields without @cypher, types without @node, @customResolver(requires)Works (details)
@query, @mutation, @selectable, @settable, @filterable, @sortable, @limit (type, field and schema level)Works (details)
@vector, Point, Duration and custom scalarsNot yet: makeSchema throws UnsupportedTypeDefsError
@populatedBy, @relayId, @coalesce, @relationship(nestedOperations, aggregate, queryDirection)Not yet: makeSchema throws UnsupportedTypeDefsError

v7 behaviour you get as well

  • { eq: null } matches nodes where the property is missing.
  • An empty filter in some, none or single (actors: { some: {} }) is ignored: it matches every node. all is not true for a node with no related nodes.
  • A cursor is base64("arrayconnection:<offset>"). An invalid after cursor returns the first page.
  • BigInt values are returned as strings, Date as yyyy-mm-dd and DateTime as ISO-8601 strings. BigInt aggregates are strings too, average included. An Int average is a Float.
  • Aggregates ignore first / after but apply the connection where. count.nodes and node aggregates count each related node once. On an empty set, count and sum are 0 and the other aggregates are null. An aggregation filter that compares a null aggregate matches nothing, even under NOT. As in v7, Date inputs are read in the time zone of the process: run the server with TZ=UTC.

To-one relationships

A relationship field that is not a list (lab: Lab @relationship(…)) gets the API v7 7.6.8 generates for it, which is smaller than the one of a list:

  • The field and its connection (labConnection) take no arguments; the connection has no aggregate. The field returns the first related node, or null.
  • where takes the target’s filter directly (lab: { state: { eq: "PUBLISHED" } }, true when the related node matches; lab: null matches nodes without one) and a connection filter (labConnection: { node, edge }). There are no some / all / … quantifiers and no aggregation filters. Authorization rules use the same filters, for example { node: { lab: { owner: { id: { eq: "$jwt.sub" } } } } }; in a rule, labConnection requires exactly one matching relationship.
  • Writes: nested create (one { node, edge }) in a create input, and nested delete in the delete argument of deleteX. As in v7 there is no connect, disconnect or update on a to-one field, and it is not part of the update input.
  • The type must be nullable: like v7, makeSchema rejects lab: Lab!.
  • Nothing checks that the graph has at most one related node (v7 does not either): a node connected from the other side twice has two, and the field returns one of them. A create input that names two members of a to-one union fails, with the v7 message.

Mutations, as in v7

  • connect creates a relationship to every node that matches where. It is a CREATE, not a MERGE: connecting a pair that is already connected adds a second relationship, whether the mutations run one after the other or at the same time. To skip nodes that are already connected, filter them out in where (for example movies: { none: { id: { eq: "…" } } }); that filter does not lock, so two concurrent mutations can still both connect.
  • In an update, the scalar operators run first, then each relationship field, element by element, in the order update, create, connect, delete, disconnect.
  • @id fields get a UUID on create. @timestamp fields are set on create and on every update of the node, even an update without an update argument. On relationships they are set by nested create and nested update, not by connect.
  • add or subtract on a missing value, an Int result beyond 32 bits, and push / pop on a missing list fail the mutation: nothing is written. v7 runs these checks with APOC; Cyphra does not need APOC, and the error message is the APOC message without its Failed to invoke procedure prefix.
  • info counts the nodes and relationships the mutation created, the relationships it removed, and the distinct nodes it deleted with every relationship attached to them. It is computed in the statement, so it does not depend on driver result counters.
  • The response of a mutation (movies { … }) is read after all of its writes. With several inputs in one createMovies, v7 can return a node as it was before a later input connected to it.

@cypher differences from v7

  • In where, a scalar @cypher field is compared on the first row the statement returns, null when there is none. v7 leaves out the node when the statement returns no row, even inside OR or NOT.
  • A filter on a @cypher field inside a filter on a @cypher field returning nodes (actors: { some: { movieCount: { gt: 1 } } }) works. v7 fails with a Neo4j “Variable not defined” error.
  • A @cypher field returning a list of enum values works. v7 fails with an enum serialization error.

Move the data model to Cyphra

The GraphQL API and the Cyphra ORM can work on the same graph. To get a schema.cyphra from the same type definitions, run cyphra import graphql. In code, compat.v7.cyphraSchema(typeDefs) returns the same conversion as a schema model, with the list of what Cyphra models differently.

The migration guide goes through the whole switch: import, migrations, the server swap and a script that compares both libraries on your operations.

Last updated on