@alxia/graphql 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ # Yoga's plugins and options
2
+
3
+ This page covers what passes through to GraphQL Yoga: its plugins and
4
+ Envelop's, error masking, batching, subscriptions over server-sent events,
5
+ and how CORS and compression meet the endpoint.
6
+
7
+ ```ts
8
+ import { alxia } from '@alxia/core';
9
+ import { graphql } from '@alxia/graphql';
10
+ import { createSchema, useExecutionCancellation } from 'graphql-yoga';
11
+
12
+ const schema = createSchema({
13
+ typeDefs: /* GraphQL */ `type Query { hello: String! }`,
14
+ resolvers: { Query: { hello: () => 'world' } },
15
+ });
16
+
17
+ const app = alxia().use((app) =>
18
+ graphql(app, {
19
+ schema,
20
+ plugins: [useExecutionCancellation()], // stop resolvers when the client goes away
21
+ batching: { limit: 5 },
22
+ logging: Bun.env['NODE_ENV'] === 'production' ? 'warn' : 'debug',
23
+ }),
24
+ );
25
+ ```
26
+
27
+ ## What passes through
28
+
29
+ `GraphQLOptions` is Yoga's `YogaServerOptions`, minus four keys the package
30
+ owns:
31
+
32
+ | Yoga's option | Here |
33
+ | --- | --- |
34
+ | `graphqlEndpoint` | set from `path` and the app's prefix ([Mounting the endpoint](endpoint.md#where-it-is-served)) |
35
+ | `graphiql` | set from `ide`; `graphiql` takes GraphiQL's options only, not `true`/`false` ([GraphiQL and Apollo Sandbox](ide.md)) |
36
+ | `cors` | `false` unless given ([CORS](#cors)) |
37
+ | `schema` | required, and checked against the app's context ([The typed context](context.md)) |
38
+
39
+ Everything else — `plugins`, `context`, `maskedErrors`, `batching`,
40
+ `logging`, `landingPage`, `healthCheckEndpoint`, `parserAndValidationCache`,
41
+ `multipart`… — goes to `createYoga` as it is, with Yoga's defaults. Its
42
+ reference is [Yoga's documentation](https://the-guild.dev/graphql/yoga-server/docs).
43
+
44
+ ## Plugins
45
+
46
+ `plugins` takes Yoga's plugins and Envelop's, in the order they run. Those
47
+ Yoga ships are imported from `graphql-yoga`; the others are packages of their
48
+ own, installed beside it:
49
+
50
+ ```sh
51
+ bun add @envelop/depth-limit @graphql-yoga/plugin-response-cache
52
+ ```
53
+
54
+ ```ts
55
+ import { useDepthLimit } from '@envelop/depth-limit';
56
+ import { useResponseCache } from '@graphql-yoga/plugin-response-cache';
57
+
58
+ graphql(app, {
59
+ schema,
60
+ plugins: [
61
+ useDepthLimit({ maxDepth: 8 }),
62
+ useResponseCache({ session: ({ request }) => request.headers.get('authorization') }),
63
+ ],
64
+ });
65
+ ```
66
+
67
+ A plugin of your own is an object of hooks, typed `Plugin`:
68
+
69
+ ```ts
70
+ import { type Plugin } from 'graphql-yoga';
71
+
72
+ const slowOperations: Plugin = {
73
+ onExecute: ({ args }) => {
74
+ const started = performance.now();
75
+ return {
76
+ onExecuteDone: () => {
77
+ const ms = performance.now() - started;
78
+ if (ms > 500) console.warn(`slow operation ${args.operationName ?? 'anonymous'}: ${ms}ms`);
79
+ },
80
+ };
81
+ },
82
+ };
83
+
84
+ graphql(app, { schema, plugins: [slowOperations] });
85
+ ```
86
+
87
+ Yoga's plugins run inside the route, after the app's route hooks: a plugin
88
+ sees only requests the hooks let through, and its context holds what they
89
+ added.
90
+
91
+ ## Errors
92
+
93
+ Yoga masks errors by default (`maskedErrors: true`): an `Error` thrown by a
94
+ resolver reaches the client as `Unexpected error.`, and its message — a
95
+ connection string, a stack — stays on the server.
96
+
97
+ ```text
98
+ 200 {"errors":[{"message":"Unexpected error.","path":["crash"],"extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"crash":null}}
99
+ ```
100
+
101
+ An error meant for the client is a `GraphQLError`; `createGraphQLError`
102
+ makes one, with a code and an HTTP status in its extensions:
103
+
104
+ ```ts
105
+ import { createGraphQLError } from 'graphql-yoga';
106
+
107
+ const resolvers = {
108
+ Query: {
109
+ admin: (_: unknown, __: unknown, { viewer }: GraphQLContext<typeof base>) => {
110
+ if (viewer !== 'admin')
111
+ throw createGraphQLError('Admins only', {
112
+ extensions: { code: 'FORBIDDEN', http: { status: 403 } },
113
+ });
114
+ return 'welcome';
115
+ },
116
+ },
117
+ };
118
+ ```
119
+
120
+ ```text
121
+ 403 {"errors":[{"message":"Admins only","path":["admin"],"extensions":{"code":"FORBIDDEN"}}],"data":{"admin":null}}
122
+ ```
123
+
124
+ `maskedErrors: false` sends every message as it is: for development only.
125
+ A resolver's error is Yoga's to answer; it does not reach the app's
126
+ `onError` hooks, which see only what fails around the endpoint.
127
+
128
+ ## Batching
129
+
130
+ `batching` lets a client send an array of operations in one `POST`, and
131
+ get an array of results:
132
+
133
+ ```ts
134
+ graphql(app, { schema, batching: { limit: 5 } });
135
+ ```
136
+
137
+ ```text
138
+ POST [{"query":"{ admin }"},{"query":"{ __typename }"}]
139
+ 200 [{"data":{"admin":"welcome"}},{"data":{"__typename":"Query"}}]
140
+ ```
141
+
142
+ ## Subscriptions
143
+
144
+ Subscriptions are served over server-sent events, Yoga's default: a
145
+ `POST` (or `GET`) with `Accept: text/event-stream` gets a stream of results.
146
+ A resolver's `subscribe` is an async iterable — an `async *` generator, or
147
+ Yoga's `createPubSub`:
148
+
149
+ ```ts
150
+ import { createPubSub, createSchema } from 'graphql-yoga';
151
+
152
+ const pubsub = createPubSub<{ message: [{ text: string }] }>();
153
+
154
+ const schema = createSchema({
155
+ typeDefs: /* GraphQL */ `
156
+ type Query { ok: Boolean }
157
+ type Mutation { send(text: String!): Boolean! }
158
+ type Subscription { message: String!, countdown(from: Int!): Int! }
159
+ `,
160
+ resolvers: {
161
+ Mutation: {
162
+ send: (_, { text }: { text: string }) => {
163
+ pubsub.publish('message', { text });
164
+ return true;
165
+ },
166
+ },
167
+ Subscription: {
168
+ message: {
169
+ subscribe: () => pubsub.subscribe('message'),
170
+ resolve: (payload: { text: string }) => payload.text,
171
+ },
172
+ countdown: {
173
+ async *subscribe(_, { from }: { from: number }) {
174
+ for (let n = from; n >= 0; n--) yield { countdown: n };
175
+ },
176
+ },
177
+ },
178
+ },
179
+ });
180
+ ```
181
+
182
+ ```sh
183
+ curl -N localhost:3000/graphql -H 'content-type: application/json' -H 'accept: text/event-stream' \
184
+ -d '{"query":"subscription { countdown(from: 2) }"}'
185
+ # event: next
186
+ # data: {"data":{"countdown":2}}
187
+ # …
188
+ ```
189
+
190
+ A subscription asked for with `Accept: application/json` is refused with
191
+ `406`. WebSockets (`graphql-ws`) are not served: a client must speak
192
+ server-sent events. `createPubSub` lives in one
193
+ process; across several, give it an event target backed by a broker, as
194
+ [Yoga's subscriptions guide](https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions)
195
+ describes.
196
+
197
+ `@alxia/compress` leaves a `text/event-stream` alone by default, so results
198
+ are sent as they are produced. A `compressible` that lets event streams in
199
+ still sends each result at once: a streamed body is flushed as it comes.
200
+
201
+ ## CORS
202
+
203
+ Yoga's own CORS is off (`cors: false`): the endpoint is a route of the app,
204
+ and `@alxia/cors` answers for the whole app, preflights included.
205
+
206
+ ```ts
207
+ import { alxia } from '@alxia/core';
208
+ import { cors } from '@alxia/cors';
209
+ import { graphql } from '@alxia/graphql';
210
+
211
+ const app = alxia()
212
+ .use(cors({ origin: 'https://app.example.com', credentials: true }))
213
+ .use((app) => graphql(app, { schema }));
214
+ // OPTIONS /graphql → 204, Access-Control-Allow-Origin: https://app.example.com
215
+ ```
216
+
217
+ Without it, a browser's preflight `OPTIONS /graphql` is a
218
+ `405 {"error":"method_not_allowed"}`, and the browser blocks the call.
219
+ Passing Yoga's `cors` turns Yoga's on for this endpoint; do not use both.
220
+
221
+ ## See also
222
+
223
+ - [Mounting the endpoint](endpoint.md): what the endpoint answers.
224
+ - [The typed context](context.md): the `context` option.
225
+ - [Troubleshooting](../troubleshooting.md): `Unexpected error.`, the `406`
226
+ and the `405`.
@@ -0,0 +1,45 @@
1
+ # Roadmap
2
+
3
+ What `@alxia/graphql` gives an app, and what is coming. This page is a
4
+ direction, not a commitment: the version something shipped in is the only
5
+ number on it. Every release, with each change it made, is in
6
+ [`CHANGELOG.md`](https://github.com/softistx/alxia/blob/develop/packages/graphql/CHANGELOG.md).
7
+
8
+ ## Now
9
+
10
+ Nothing scheduled yet.
11
+
12
+ ## Next
13
+
14
+ Nothing scheduled yet.
15
+
16
+ ## Later
17
+
18
+ Nothing scheduled yet.
19
+
20
+ ## Shipped
21
+
22
+ ### 0.1.0
23
+
24
+ - **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
25
+ `GET` and `POST` `/graphql`, or any `path`, under the app's prefix and
26
+ the prefix of every app it is mounted into. The endpoint runs behind the
27
+ app's hooks like any route: a guard declared before it guards it, and its
28
+ reply is part of the endpoint's type.
29
+ - **The app's context in every resolver, typed and checked.**
30
+ `GraphQLContext<typeof app>` types a schema with Yoga's context and
31
+ everything the app's hooks add — a user, a database handle — plus `set`,
32
+ through which a resolver sets a header or a cookie. A schema whose
33
+ resolvers read what the app does not build is a compile error naming the
34
+ missing field, and `GraphQLContext` of anything but an app is a message
35
+ that fails the first resolver reading a field.
36
+ - **Yoga whole.** Every Yoga option passes through: its plugins and
37
+ Envelop's, the `context` factory, error masking, batching, logging.
38
+ Subscriptions are served over server-sent events.
39
+ - **An IDE, or none.** A browser at the endpoint gets Yoga's GraphiQL by
40
+ default, or Apollo Sandbox pointed at the address it was opened at —
41
+ `https` behind a proxy that terminates TLS — each with
42
+ a `Content-Security-Policy` that lets it load; `ide: false` turns it off.
43
+ `renderSandbox` and `SANDBOX_POLICY` serve the Sandbox page anywhere else.
44
+ - **CORS left to the app.** Yoga's own CORS is off, so `@alxia/cors`
45
+ answers for the whole app, the endpoint included.
@@ -0,0 +1,396 @@
1
+ # Troubleshooting
2
+
3
+ Each entry is headed by the text you see: a TypeScript error, an exception
4
+ thrown when the app is built, or a response from the endpoint. Problems that
5
+ show no message, or only the browser's, are under [Traps](#traps), by
6
+ symptom.
7
+
8
+ **Install**
9
+
10
+ - [`Cannot find package 'graphql-yoga' from '…/@alxia/graphql/dist/index.js'`](#cannot-find-package-graphql-yoga-from-alxiagraphqldistindexjs)
11
+
12
+ **Types**
13
+
14
+ - [`the schema's resolvers read a context the app does not build: missing …`](#the-schemas-resolvers-read-a-context-the-app-does-not-build-missing-)
15
+ - [`Property 'viewer' does not exist on type '{ readonly '~error': "GraphQLContext needs the type of an app: GraphQLContext<typeof app>"; } & YogaInitialContext'`](#property-viewer-does-not-exist-on-type--readonly-error-graphqlcontext-needs-the-type-of-an-app-graphqlcontexttypeof-app---yogainitialcontext)
16
+ - [`Property 'viewer' does not exist on type 'YogaInitialContext'`](#property-viewer-does-not-exist-on-type-yogainitialcontext)
17
+ - [`Property 'query' does not exist on type 'YogaInitialContext & ServerContext<…>'`](#property-query-does-not-exist-on-type-yogainitialcontext--servercontext)
18
+ - [`Type 'true' is not assignable to type 'GraphiQLOptions | GraphiQLOptionsFactory<…> | undefined'`](#type-true-is-not-assignable-to-type-graphiqloptions--graphiqloptionsfactory--undefined)
19
+ - [`'graphqlEndpoint' does not exist in type 'GraphQLOptions<…>'`](#graphqlendpoint-does-not-exist-in-type-graphqloptions)
20
+ - [``Type '"gql"' is not assignable to type '`/${string}`'``](#type-gql-is-not-assignable-to-type-string)
21
+
22
+ **Startup**
23
+
24
+ - [`TypeError: GET /graphql is declared twice`](#typeerror-get-graphql-is-declared-twice)
25
+
26
+ **Responses**
27
+
28
+ - [`200 {"errors":[{"message":"Unexpected error.", … "code":"INTERNAL_SERVER_ERROR"}}]}`](#200-errorsmessageunexpected-error--codeinternal_server_error)
29
+ - [`405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`](#405-errormethod_not_allowed-on-options-graphql)
30
+ - [`405 {"errors":[{"message":"Can only perform a mutation operation from a POST request."}]}`](#405-errorsmessagecan-only-perform-a-mutation-operation-from-a-post-request)
31
+ - [`406` with an empty body](#406-with-an-empty-body)
32
+ - [`{"errors":[{"message":"Must provide query string."}]}`](#errorsmessagemust-provide-query-string)
33
+
34
+ **Traps**
35
+
36
+ - [The endpoint answers without a guard declared after it](#the-endpoint-answers-without-a-guard-declared-after-it)
37
+ - [A WebSocket client cannot connect: `Expected 101 status code`](#a-websocket-client-cannot-connect-expected-101-status-code)
38
+ - [The IDE page is blank](#the-ide-page-is-blank)
39
+ - [GraphiQL is served in production](#graphiql-is-served-in-production)
40
+
41
+ ## Install
42
+
43
+ ### `Cannot find package 'graphql-yoga' from '…/@alxia/graphql/dist/index.js'`
44
+
45
+ **When:** importing `@alxia/graphql`, before any of your code runs. The same
46
+ message names `graphql` when that one is missing; `tsc` reports either as
47
+ `TS2307: Cannot find module 'graphql-yoga'`.
48
+
49
+ **Why:** `graphql-yoga` and `graphql` are peers: the package declares no
50
+ dependency, so the app installs them.
51
+
52
+ **Fix:**
53
+
54
+ ```sh
55
+ bun add @alxia/graphql graphql-yoga graphql
56
+ ```
57
+
58
+ With `graphql` 17, `graphql-yoga` must be 5.22 or later: an older Yoga
59
+ declares `graphql ^15.2.0 || ^16.0.0`, and `bun install` warns about an
60
+ incorrect peer. `bun add graphql-yoga@latest` updates it.
61
+
62
+ ## Types
63
+
64
+ These are what `tsc` prints. Codes are those with `exactOptionalPropertyTypes`
65
+ off; with it on, an assignment error is `TS2375` instead of `TS2322`, with
66
+ the same last line.
67
+
68
+ ### `the schema's resolvers read a context the app does not build: missing …`
69
+
70
+ **When:** `graphql(app, { schema })`, where `…` names a field: `missing user`,
71
+ `missing viewer`. With several missing, each is a member of a union.
72
+
73
+ ```text
74
+ error TS2322: Type 'GraphQLSchemaWithContext<…>' is not assignable to type 'GraphQLSchema & { _context?: … } & "the schema's resolvers read a context the app does not build: missing user"'.
75
+ ```
76
+
77
+ **Why:** the schema was typed with `GraphQLContext<typeof base>`, and its
78
+ resolvers read what `base`'s hooks add, but `graphql` was given an app that
79
+ does not run those hooks: another app, or the endpoint declared before the
80
+ `derive` or the guard.
81
+
82
+ **Fix:** mount the endpoint on the app the schema was typed from, after its
83
+ hooks ([The typed context](guide/context.md)):
84
+
85
+ ```ts
86
+ const base = alxia().use(bearer({ jwt })); // adds user
87
+ const schema = createSchema<GraphQLContext<typeof base>>({ … });
88
+ const app = base.use((app) => graphql(app, { schema })); // not alxia().use(…)
89
+ ```
90
+
91
+ **When the missing field comes from the `context` option** — `missing
92
+ loaders`, though `context` returns `loaders` — the function reads its
93
+ argument without a type annotation, so TypeScript does not infer what it
94
+ returns. Annotate the argument:
95
+
96
+ ```ts
97
+ graphql(app, {
98
+ schema,
99
+ context: ({ users }: GraphQLContext<typeof base>) => ({ loaders: createLoaders(users) }),
100
+ });
101
+ ```
102
+
103
+ ### `Property 'viewer' does not exist on type '{ readonly '~error': "GraphQLContext needs the type of an app: GraphQLContext<typeof app>"; } & YogaInitialContext'`
104
+
105
+ **When:** a resolver of a schema typed `createSchema<GraphQLContext<X>>`
106
+ reads a field, and `X` is not an alxia app: a function returning one, a
107
+ schema, a route. Passed to `graphql(app, { schema })` anyway, the schema is
108
+ refused with `missing ~error`.
109
+
110
+ **Why:** `GraphQLContext` reads the context from an app's type. Given
111
+ anything else, it is this message, and holds none of the app's fields.
112
+
113
+ **Fix:** give it the app's type:
114
+
115
+ ```ts
116
+ const makeApp = () => alxia().decorate({ users });
117
+ const base = makeApp();
118
+ createSchema<GraphQLContext<typeof base>>({ … }); // not GraphQLContext<typeof makeApp>
119
+ ```
120
+
121
+ ### `Property 'viewer' does not exist on type 'YogaInitialContext'`
122
+
123
+ **When:** a resolver of a schema created with `createSchema({ … })`, no type
124
+ argument, reads what the app's hooks add.
125
+
126
+ **Why:** an untyped schema's context is Yoga's alone. The field is there at
127
+ runtime; its type is not.
128
+
129
+ **Fix:**
130
+
131
+ ```ts
132
+ const schema = createSchema<GraphQLContext<typeof base>>({ … });
133
+ ```
134
+
135
+ ### `Property 'query' does not exist on type 'YogaInitialContext & ServerContext<…>'`
136
+
137
+ **When:** a resolver reads `query`, `headers`, `cookies`, `body`, `reply` or
138
+ `redirect` from its context, as a route handler would.
139
+
140
+ **Why:** those are the route's, and mean nothing to a resolver: the request
141
+ is a GraphQL request, and a resolver answers a field, not the request.
142
+ `params` is there, but it is Yoga's: the GraphQL `query`, `variables` and
143
+ `operationName`.
144
+
145
+ **Fix:** read a header or a cookie from `request`, and set them on the
146
+ response with `set`:
147
+
148
+ ```ts
149
+ const resolvers = {
150
+ Query: {
151
+ locale: (_: unknown, __: unknown, { request, set }: GraphQLContext<typeof base>) => {
152
+ set.headers.set('vary', 'accept-language');
153
+ return request.headers.get('accept-language') ?? 'en';
154
+ },
155
+ },
156
+ };
157
+ ```
158
+
159
+ ### `Type 'true' is not assignable to type 'GraphiQLOptions | GraphiQLOptionsFactory<…> | undefined'`
160
+
161
+ **When:** `graphql(app, { schema, graphiql: true })`, or `false`.
162
+
163
+ **Why:** `ide` decides whether there is a GraphiQL; `graphiql` takes only
164
+ its options.
165
+
166
+ **Fix:**
167
+
168
+ ```ts
169
+ graphql(app, { schema, ide: 'graphiql', graphiql: { title: 'Users API' } });
170
+ graphql(app, { schema, ide: false });
171
+ ```
172
+
173
+ ### `'graphqlEndpoint' does not exist in type 'GraphQLOptions<…>'`
174
+
175
+ **When:** passing Yoga's `graphqlEndpoint`.
176
+
177
+ ```text
178
+ error TS2353: Object literal may only specify known properties, and 'graphqlEndpoint' does not exist in type 'GraphQLOptions<…>'.
179
+ ```
180
+
181
+ **Why:** the endpoint is a route of the app, and its path is joined to the
182
+ app's prefix; Yoga is told the result.
183
+
184
+ **Fix:**
185
+
186
+ ```ts
187
+ graphql(app, { schema, path: '/gql' }); // served at <prefix>/gql
188
+ ```
189
+
190
+ ### ``Type '"gql"' is not assignable to type '`/${string}`'``
191
+
192
+ **When:** `path` does not start with `/`.
193
+
194
+ **Fix:**
195
+
196
+ ```ts
197
+ graphql(app, { schema, path: '/gql' });
198
+ ```
199
+
200
+ ## Startup
201
+
202
+ ### `TypeError: GET /graphql is declared twice`
203
+
204
+ **When:** building the app, at the second `graphql(…)` on it, or at a
205
+ `get('/graphql', …)` beside the endpoint.
206
+
207
+ **Why:** each `graphql` call declares `GET` and `POST` at its `path`, and
208
+ two endpoints with the default path collide. `use((app) => graphql(app, …))`
209
+ declares the routes on the app it is called on, so calling it twice on the
210
+ same `base` — for two variants of an app — declares them twice there.
211
+
212
+ **Fix:** a `path` for each endpoint, or one `graphql` per app:
213
+
214
+ ```ts
215
+ const app = alxia()
216
+ .use((app) => graphql(app, { schema }))
217
+ .use((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
218
+ ```
219
+
220
+ ## Responses
221
+
222
+ ### `200 {"errors":[{"message":"Unexpected error.", … "code":"INTERNAL_SERVER_ERROR"}}]}`
223
+
224
+ **When:** a resolver throws an `Error`, or rejects.
225
+
226
+ **Why:** Yoga masks errors by default, so a database message or a stack
227
+ never reaches a client. The original error is logged by Yoga's logger,
228
+ unless `logging` is `false`.
229
+
230
+ **Fix:** throw a `GraphQLError` for what the client should read; it passes
231
+ unmasked, with its code and status
232
+ ([Errors](guide/yoga.md#errors)):
233
+
234
+ ```ts
235
+ import { createGraphQLError } from 'graphql-yoga';
236
+
237
+ throw createGraphQLError('Admins only', {
238
+ extensions: { code: 'FORBIDDEN', http: { status: 403 } },
239
+ });
240
+ ```
241
+
242
+ `maskedErrors: false` shows every message, for development only.
243
+
244
+ ### `405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`
245
+
246
+ **When:** a browser on another origin calls the endpoint; its preflight
247
+ fails and the console reports a CORS error.
248
+
249
+ **Why:** Yoga's CORS is off, and the app answers no `OPTIONS` without a
250
+ CORS plugin.
251
+
252
+ **Fix:** `@alxia/cors`, for the whole app ([CORS](guide/yoga.md#cors)):
253
+
254
+ ```ts
255
+ import { cors } from '@alxia/cors';
256
+
257
+ const app = alxia()
258
+ .use(cors({ origin: 'https://app.example.com', credentials: true }))
259
+ .use((app) => graphql(app, { schema }));
260
+ ```
261
+
262
+ ### `405 {"errors":[{"message":"Can only perform a mutation operation from a POST request."}]}`
263
+
264
+ **When:** a mutation sent as `GET /graphql?query=mutation …`. The body also
265
+ carries `"extensions":{"code":"BAD_REQUEST"}`.
266
+
267
+ **Why:** Yoga refuses mutations over `GET`, which a link or a cache could
268
+ replay.
269
+
270
+ **Fix:** send it as a `POST`:
271
+
272
+ ```ts
273
+ await fetch('/graphql', {
274
+ method: 'POST',
275
+ headers: { 'content-type': 'application/json' },
276
+ body: JSON.stringify({ query: 'mutation { login(name: "ada") }' }),
277
+ });
278
+ ```
279
+
280
+ ### `406` with an empty body
281
+
282
+ **When:** a subscription sent with `Accept: application/json`; or a
283
+ request whose `Accept` allows only `text/html` (no `*/*`, no
284
+ `application/json`), such as `curl -H 'accept: text/html'`, where no IDE
285
+ page is served — `ide: false`, or `ide: 'apollo-sandbox'` with a `?query=`
286
+ in the URL. A browser sends `*/*` too, and gets JSON there.
287
+
288
+ **Why:** a subscription is a stream of results: Yoga sends it only to a
289
+ client that accepts `text/event-stream`, and has no other representation
290
+ to offer. Likewise, a result has no HTML representation: a client asking
291
+ only for HTML, with no IDE page to serve it, gets nothing it accepts.
292
+
293
+ **Fix:** for a subscription, accept `text/event-stream`:
294
+
295
+ ```ts
296
+ await fetch('/graphql', {
297
+ method: 'POST',
298
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
299
+ body: JSON.stringify({ query: 'subscription { countdown(from: 3) }' }),
300
+ });
301
+ ```
302
+
303
+ For a client that asks only for HTML, accept `application/json` (or
304
+ `*/*`) where no IDE is served, or keep an IDE where one is wanted — see
305
+ [GraphiQL and Apollo Sandbox](guide/ide.md).
306
+
307
+ ### `{"errors":[{"message":"Must provide query string."}]}`
308
+
309
+ **When:** a `GET` with no `query` parameter from a client that does not ask
310
+ for HTML — or from a browser when `ide` is `false` — or a `POST` whose JSON
311
+ body has no `query`. The body carries
312
+ `"extensions":{"code":"BAD_REQUEST"}`.
313
+
314
+ **Why:** the request reached Yoga, with nothing to run. A `GET` from a
315
+ browser gets the IDE page instead, unless `ide` is `false`; a client
316
+ asking only for HTML gets a [`406`](#406-with-an-empty-body) where no page is
317
+ served.
318
+
319
+ **Fix:** send the operation as `query`, in the body or the URL:
320
+
321
+ ```ts
322
+ await app.request(`/graphql?query=${encodeURIComponent('{ me }')}`, {
323
+ headers: { accept: 'application/json' },
324
+ });
325
+ ```
326
+
327
+ ## Traps
328
+
329
+ ### The endpoint answers without a guard declared after it
330
+
331
+ **When:** `.use((app) => graphql(app, { schema }))` comes before
332
+ `.use(bearer(…))` or a guarding `derive`: the endpoint answers anonymous
333
+ requests, and its resolvers read no `user`.
334
+
335
+ **Why:** a route hook applies to the routes declared after it. The endpoint
336
+ is a route, declared where `graphql` is called. A schema typed from the
337
+ guarded app is refused (`missing user`); an untyped one is not.
338
+
339
+ **Fix:** declare the guard first:
340
+
341
+ ```ts
342
+ const base = alxia().use(bearer({ jwt }));
343
+ const app = base.use((app) => graphql(app, { schema }));
344
+ ```
345
+
346
+ ### A WebSocket client cannot connect: `Expected 101 status code`
347
+
348
+ **When:** a `graphql-ws` client, or GraphiQL with
349
+ `subscriptionsProtocol: 'WS'`, opens `ws://…/graphql`. Bun's client prints
350
+ `Expected 101 status code`; a browser reports the WebSocket connection as
351
+ failed.
352
+
353
+ **Why:** the endpoint serves subscriptions over server-sent events only;
354
+ it never upgrades to a WebSocket.
355
+
356
+ **Fix:** subscribe over SSE, with `Accept: text/event-stream`
357
+ ([Subscriptions](guide/yoga.md#subscriptions)), and leave GraphiQL's
358
+ protocol at SSE:
359
+
360
+ ```ts
361
+ graphql(app, { schema, graphiql: { subscriptionsProtocol: 'SSE' } });
362
+ ```
363
+
364
+ ### The IDE page is blank
365
+
366
+ **When:** GraphiQL or Apollo Sandbox loads an empty page, and the browser
367
+ console reports scripts refused by the `Content-Security-Policy`.
368
+
369
+ **Why:** the endpoint sends the IDE with a policy that lets it load its
370
+ scripts from `unpkg.com` or Apollo's CDN. A hook of the app that sets its
371
+ own `Content-Security-Policy` on every response replaces it.
372
+ `@alxia/secure-headers` does not: it keeps a policy a response already has.
373
+
374
+ **Fix:** set the app's policy only where none is set
375
+ ([With `@alxia/secure-headers`](guide/ide.md#with-alxiasecure-headers)):
376
+
377
+ ```ts
378
+ app.onResponse((response) =>
379
+ withHeaders(response, (headers) => {
380
+ if (!headers.has('content-security-policy'))
381
+ headers.set('content-security-policy', "default-src 'self'");
382
+ }),
383
+ );
384
+ ```
385
+
386
+ ### GraphiQL is served in production
387
+
388
+ **When:** a browser opening the production endpoint gets GraphiQL.
389
+
390
+ **Why:** `ide` is `'graphiql'` by default.
391
+
392
+ **Fix:**
393
+
394
+ ```ts
395
+ graphql(app, { schema, ide: Bun.env['NODE_ENV'] === 'production' ? false : 'graphiql' });
396
+ ```