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-driverIt 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.
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 });| Option | Description |
|---|---|
typeDefs | Your v7 type definitions (@node, @relationship, …), as a string. |
driver | A neo4j-driver driver. |
client | A CyphraClient, instead of driver, to share the connection of your app. |
database | Database name used with driver. Default: the default database. A request’s context.sessionConfig.database takes precedence. |
debug | Log 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:
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:
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’squeryevents and spans name the engine operation and model (findManyonMovie) instead ofgraphql.read/graphql.write. - A root connection that selects both a page (
edges/pageInfo) andtotalCountreads 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:
export const schema = compat.v7.makeSchema({
typeDefs,
driver,
features: { authorization: { key: process.env.JWT_SECRET! } },
});const { handleRequest } = createYoga({
schema,
graphqlEndpoint: "/api/graphql",
fetchAPI: { Response },
context: ({ request }) => ({ token: request.headers.get("authorization") ?? undefined }),
});features.authorization | Description |
|---|---|
key | A secret (HS256, HS384, HS512), { url } of a JWKS endpoint (keys are cached), or a function of the context that returns one of the two. |
verifyOptions | Passed to jwtVerify of jose: issuer, audience, algorithms, clockTolerance, … |
verify | false 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 overtoken.- 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 withextend schema @authentication(…). It fails withUnauthenticatedbefore anything runs.@authorization(filter: [...], validate: [...])on a type or a field, withoperations(READ,AGGREGATE,CREATE,UPDATE,DELETE,CREATE_RELATIONSHIP,DELETE_RELATIONSHIP),requireAuthenticationand, forvalidate,when: [BEFORE, AFTER]. A failedvalidaterule fails the root field withForbidden.where: { node: …, jwt: … }withAND/OR/NOT, any filter of the type innode(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 afilterrule, and fails itsvalidaterules. - Rules only cover what is selected or written.
wherefilters,sortand 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
aggregateuses theAGGREGATErules, not theREADones: giveAGGREGATEthe samefilterasREADunless counts may differ. - An update that only writes relationships of a node (
connect,disconnect, …) does not apply that node’sUPDATErules; the rules of the related type and the relationship rules (CREATE_RELATIONSHIP,DELETE_RELATIONSHIP) still apply. - The response of a
createmutation returns the created nodes without theirREADrules (nested selections apply them). The response of anupdateapplies them. CREATErules are checked after the write (validatewithwhen: [AFTER]), there are nofilterrules forCREATE. Onconnect, the source node is only checked after the relationship is created.- A
jwtpassed in the context is trusted, and@jwtClaimpaths only apply to tokens verified fromtoken, 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/ORelement,nodeandjwtmust both hold. v7 combines them with the element’s operator, soOR: [{ node: …, jwt: … }]passes when either holds. NOTworks at the top of a rule (v7 throws).- A
validaterule that evaluates tonull(a compared property is missing) fails withForbidden. v7 fails with an APOC error. - A
$contextvalue that is not in the context isnull, so the comparison matches nothing. v7 fails with a Neo4j “Expected parameter” error. - In
@authentication(jwt: …),eqdoes not consider a list equal to a string. - A rule that does not fit its type (unknown field, wrong operator) makes
makeSchemathrow, and@authentication/@authorizationon 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")
}thisis the node (or the relationship, on relationship properties) the field belongs to.$namerefers to an argument of the field. Each value is passed as a parameter, never written into the statement: a missing ornullargument becomesNULL, and default values apply.$jwtis the JWT of the request ({}when it is not authenticated), and the keys ofcontext.cypherParamsare passed as parameters too.- Scalar
@cypherfields without arguments can be used inwhereandsort, like v7 generates them. Fields that return nodes can be filtered withsome/all/none/single(lists) or with a node filter (one node). - Nodes returned by a statement get the
READrules of their type, and the selection works as for any node: nested relationships, connections and other@cypherfields. Queryfields run in a read transaction,Mutationfields in a write transaction. Their@authentication(on the field or ontype Query/type Mutation) is checked first.
As in v7:
- A scalar field takes the
columnNamevalue 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
QueryorMutationfield that is not a list returns the first row, ornull. allon 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:
QueryandMutationfields without@cypher;- object, input, enum and union types without
@node, which are added to the schema as written; @customResolverfields of@nodetypes, 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
@customResolverfield is left out of the generated Cypher and of everywhere,sort, create and update input. Therequiresselection (fields, relationships and connections of the type) is always fetched, and the resolver is called with the parent object. - Before a
QueryorMutationresolver runs,context.jwtis set to the payload of the verifiedcontext.token(unless you passedjwt) andcontext.executionContextto the driver (unless you passed one), so your resolvers, nested ones included, can read them. @authenticationontype Query/type Mutation, onextend schemaor on the field applies to fields served by your resolvers.makeSchemathrows"X" defined in resolvers, but not in schemafor a resolver of an unknown type or field, and warns when a@customResolverfield has no resolver.Int,FloatandIDfields convert Neo4j integers your resolvers return.
Differences from v7:
@authenticationapplies to everyQuery/Mutationfield 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,
@nodetypes, unions and types without@nodeof the type definitions, not generated types such asLabWhere. Resolvers for scalar or enum types (internal enum values) andtype Subscriptionfields are not supported yet.
Full-text search
@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
whereselects members:{ Movie: { … } }returns movies only,{ Book: {} }every book, and{}(or nowhere) every member. Each member gets its ownREADrules. limitandoffsetapply to the rows of all members together, in no particular order: there is nosorton a union list. A connection sorts on edge properties only (sort: [{ edge: … }]), and has noaggregate.limit: 0is 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:
totalCountcounts those edges. - Relationship filters test each member named in the filter:
someis true when one of them matches,allandnonemust hold for every member named, andsinglecombines the members withXOR(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 fornoneand that there is one forsome. - Nested
create,connect,update,disconnectanddeletetake one input per member (favorites: { Movie: […], Book: […] }), with the member’swhereand 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
LearningActivitywhen it has every label of one implementation:Labnodes need bothLabandLearningActivityhere. Give the implementations a shared label in@node(labels)to find them all with one label in Cypher. wheretakes the interface fields, the declared relationships andtypename: [Lab, Quiz](the implementations to keep;[]keeps all).sort,limit,offset, cursors andaggregateapply 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 }). @authorizationgoes on the implementations (v7 rejects it on interfaces): reading through the interface applies each implementation’s rules to its nodes.@authenticationof every implementation applies to reads through the interface.- Writes go to implementations.
createthrough a relationship to the interface is keyed by implementation (node: { Lab: { title: "…" } });connect,update,disconnectanddeleteapply the interfacewhere(withtypename) to the nodes of each implementation. - A relationship an interface declares uses the interface’s connection types on every
implementation (
Lab.tracksConnection: LearningActivityTracksConnection!, withoutaggregate). Its connectionwhereandsort, and edge inputs written through the interface, key edge properties by properties type (edge: { ContainsProperties: { position: { eq: 1 } } }), andpropertiesis a union of the properties types: read it with... on ContainsProperties. @query,@pluraland@limitwork on interfaces, and@selectable,@settable,@filterable,@sortableon 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:
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:
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
@nodetype. @subscription(events: [...])on a type, orextend schema @subscription(...)for every type, chooses the fields. Without either, there is noSubscriptiontype.wherefilters created events on the new properties, updated and deleted events on the previous ones. It has no relationship or@cypherfilters.@cypherfields are in the payload and arenull.@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 unlessrequireAuthentication: false.@authorizationdoes not filter events (v7 prints a warning; so does Cyphra). On a field,@subscriptionsAuthorizationhas no effect.@authentication(operations: [SUBSCRIBE])checks the subscriber when it subscribes, and selecting the payload checksREAD@authenticationof 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,falseor""matches: v7 skips falsy values, soavailable: { 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,DateandDateTimecompare by value. @aliasfields 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.
| Directive | Where | Effect |
|---|---|---|
@mutation(operations: [CREATE, UPDATE, DELETE]) | type, or extend schema | Only 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 schema | read: the root list query (users). connection: edges / totalCount / pageInfo of usersConnection. aggregate: its aggregate field. |
@selectable(onRead: true, onAggregate: false) | field, relationship, relationship property | onRead: 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 property | The field is in the create / update inputs (root and nested). |
@filterable(byValue: true, byAggregate: false) | field, relationship, relationship property | byValue: the field is in where inputs. byAggregate: it is in aggregation filters. |
@sortable(byValue: true) | field | The field is in sort inputs. A type with no sortable field has no sort argument at all. |
@limit(default, max) | type | Page 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:
@queryalone turnsaggregateoff,@selectablealone turnsonAggregateoff and@filterablealone turns aggregation filters off. @query/@mutationgo either on the schema or on types, not both (makeSchemathrows, like v7).@query(read: false)on a type also removes its connection, unlessconnection: true.- A list relationship with
@selectable(onRead: false)keeps its…Connectionfield with onlyaggregate. On to-one relationships,@filterablehas no effect (v7 always generates their filters).@sortablehas no effect on relationship properties: v7 lists every property in the edgesortinput. - A type with nothing settable gets
_emptyInput: Booleanin its create / update input. - A root field hidden by
@query/@mutationcan be defined intype Query/type Mutationand served by your resolvers, e.g. acreateUsersthat 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 (makeSchemathrows, like v7).@limitapplies to root and nested lists and connections,@cypherfields returning a list of the type, full-text queries and the nodes returned bycreate/updatemutations. It does not apply to union queries oraggregate. With@limit,pageInfo.hasNextPageis computed from the requestedfirst(it isfalsewhenfirstis not given), like v7.
These directives shape the API; they are not access control. As in v7:
@mutation(operations: [])removescreateUsers,updateUsersanddeleteUsers, 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@authorizationrule 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: 0counts as “not given” (thedefault, capped bymax). v7 ignores0after applying@limitand returns every node, which bypassesmax. 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
nullwhere v7 expects a Boolean, an invalid@limitor an unknown@mutationoperation makemakeSchemathrow.
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.
| Feature | Status |
|---|---|
Generated schema: queries, connections, every where / sort / mutation input, aggregate types, deprecated field_OPERATOR fields | Works: the printed SDL is identical to v7, in its order |
List queries: movies(where, sort, limit, offset), pluralization like v7, @plural | Works |
Filters on String, ID, Int, Float, BigInt, Boolean, Date, DateTime, enums and lists, with AND / OR / NOT | Works |
Relationship filters some / all / none / single, connection filters on node and edge | Works |
Connections: totalCount, pageInfo, cursors with first / after, nested connections with edge properties, sort and filter on edges | Works |
Nested relationship fields with where, sort, limit, offset | Works |
To-one relationships (lab: Lab @relationship(…)): field, connection, where, nested create / delete, authorization rules through them | Works (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 selection | Works |
Nested writes: create, connect, disconnect, update, delete (nested in each other), edge properties | Works |
Update operators: set, add, subtract, multiply, divide, push, pop and the deprecated field_SET / field_INCREMENT / … | Works |
@id, @timestamp, @default | Works |
@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 fields | Works (details) |
@fulltext queries: score, where, sort, first / after | Works (details) |
Unions: root query, relationships to unions with edge properties, member-keyed where and nested writes. cyphra import graphql maps them to Cyphra unions | Works (details) |
Interfaces: root queries and connections, typename filters, relationships to interfaces, @declareRelationship, nested writes, per-implementation @authorization | Works (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 scalars | Not 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,noneorsingle(actors: { some: {} }) is ignored: it matches every node.allis not true for a node with no related nodes. - A cursor is
base64("arrayconnection:<offset>"). An invalidaftercursor returns the first page. BigIntvalues are returned as strings,Dateasyyyy-mm-ddandDateTimeas ISO-8601 strings. BigInt aggregates are strings too,averageincluded. An Intaverageis a Float.- Aggregates ignore
first/afterbut apply the connectionwhere.count.nodesandnodeaggregates count each related node once. On an empty set,countandsumare0and the other aggregates arenull. An aggregation filter that compares anullaggregate matches nothing, even underNOT. As in v7,Dateinputs are read in the time zone of the process: run the server withTZ=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 noaggregate. The field returns the first related node, ornull. wheretakes the target’s filter directly (lab: { state: { eq: "PUBLISHED" } }, true when the related node matches;lab: nullmatches nodes without one) and a connection filter (labConnection: { node, edge }). There are nosome/all/ … quantifiers and no aggregation filters. Authorization rules use the same filters, for example{ node: { lab: { owner: { id: { eq: "$jwt.sub" } } } } }; in a rule,labConnectionrequires exactly one matching relationship.- Writes: nested
create(one{ node, edge }) in a create input, and nesteddeletein thedeleteargument ofdeleteX. As in v7 there is noconnect,disconnectorupdateon a to-one field, and it is not part of the update input. - The type must be nullable: like v7,
makeSchemarejectslab: 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
connectcreates a relationship to every node that matcheswhere. It is aCREATE, not aMERGE: 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 inwhere(for examplemovies: { 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. @idfields get a UUID on create.@timestampfields are set on create and on every update of the node, even an update without anupdateargument. On relationships they are set by nestedcreateand nestedupdate, not byconnect.addorsubtracton a missing value, anIntresult beyond 32 bits, andpush/popon 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 itsFailed to invoke procedureprefix.infocounts 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 onecreateMovies, v7 can return a node as it was before a later input connected to it.
@cypher differences from v7
- In
where, a scalar@cypherfield is compared on the first row the statement returns,nullwhen there is none. v7 leaves out the node when the statement returns no row, even insideORorNOT. - A filter on a
@cypherfield inside a filter on a@cypherfield returning nodes (actors: { some: { movieCount: { gt: 1 } } }) works. v7 fails with a Neo4j “Variable not defined” error. - A
@cypherfield 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.