graphql-upload-nextjs 3.0.0 → 3.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.
package/CONTRIBUTING.md CHANGED
@@ -7,9 +7,10 @@ Thank you for dedicating time to improve `graphql-upload-nextjs`.
7
7
  Initialize, build, and test the core package:
8
8
 
9
9
  ```bash
10
- npm install
10
+ npm ci
11
11
  npm run build
12
12
  npm test
13
+ npm run test:types
13
14
 
14
15
  ```
15
16
 
@@ -17,9 +18,11 @@ Verify the example application independently:
17
18
 
18
19
  ```bash
19
20
  cd examples/example-graphql-upload-nextjs
20
- npm install
21
+ npm ci
21
22
  npm run build
22
23
  npm run lint
24
+ cd ../..
25
+ npm run test:integration
23
26
 
24
27
  ```
25
28
 
@@ -42,4 +45,4 @@ Clear, reproducible reports lead to faster fixes. When opening an issue, please
42
45
  * A minimal reproduction repository or the exact request payload.
43
46
  * A concise description of the expected and actual behavior.
44
47
 
45
- For security vulnerabilities, please refer directly to `SECURITY.md` for proper disclosure steps.
48
+ For security vulnerabilities, please refer directly to `SECURITY.md` for proper disclosure steps.
package/README.md CHANGED
@@ -1,326 +1,147 @@
1
1
  # graphql-upload-nextjs
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/graphql-upload-nextjs.svg)](https://www.npmjs.com/package/graphql-upload-nextjs)
4
- [![CI](https://github.com/lafittemehdy/graphql-upload-nextjs/actions/workflows/ci.yml/badge.svg)](https://github.com/lafittemehdy/graphql-upload-nextjs/actions/workflows/ci.yml)
5
- [![license](https://img.shields.io/npm/l/graphql-upload-nextjs.svg)](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE)
6
- [![GraphQL multipart request spec](https://img.shields.io/badge/spec-graphql--multipart--request-blue)](https://github.com/jaydenseric/graphql-multipart-request-spec)
7
- [![Node.js](https://img.shields.io/badge/node-%3E%3D22.13-brightgreen)](https://nodejs.org)
8
- [![TypeScript](https://img.shields.io/badge/TypeScript-6-blue)](https://www.typescriptlang.org)
9
-
10
- A [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec) implementation for [Next.js](https://nextjs.org) App Router with [Apollo Server](https://www.apollographql.com/docs/apollo-server). Enables file uploads via GraphQL mutations using the `Upload` scalar, with built-in MIME type verification via magic bytes.
11
-
12
- ## Features
13
-
14
- - Implements the [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec).
15
- - Designed for Next.js App Router route handlers.
16
- - Supports single file uploads, multiple file uploads, and operation batching.
17
- - File deduplication (one file mapped to multiple operation paths).
18
- - MIME type verified via magic bytes using [file-type](https://npm.im/file-type), not trusting client headers.
19
- - Unknown binary files fall back to `application/octet-stream` instead of the client-provided MIME type.
20
- - Configurable `allowedTypes`, `maxFileSize`, and `maxFiles`.
21
- - Only reads 4KB for MIME detection — streams the rest directly from `Blob`.
22
- - Spec-compatible property names: `filename`, `mimetype`, `encoding`, `createReadStream`.
3
+ The `graphql-upload-nextjs` package supports the [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec) for the Next.js App Router and Apollo Server. It has an `Upload` scalar, buffered uploads and an optional streaming API. The package declares Node.js 22.13+, Apollo Server 5, GraphQL 16 and Next.js 16 support. Check the engine requirements of your chosen dependency versions too, as they may require a newer Node.js patch release.
23
4
 
24
5
  ## Installation
25
6
 
26
- ```bash
7
+ Install the package and its integrations via npm:
8
+
9
+ ```sh
27
10
  npm install graphql-upload-nextjs @apollo/server @as-integrations/next graphql next
28
11
  ```
29
12
 
30
- ## Migrating from graphql-upload
31
-
32
- [graphql-upload](https://github.com/jaydenseric/graphql-upload) uses Express/Koa middleware that is incompatible with Next.js App Router route handlers. This package provides the same `Upload` scalar and file object interface for the Next.js environment.
13
+ ## Choosing an upload API
33
14
 
34
- Property names match the original: `filename`, `mimetype`, `encoding`, `createReadStream`. An additional `fileSize` property is also available.
15
+ The package offers two upload APIs: `uploadProcess` and `uploadProcessStreaming`.
35
16
 
36
- **Before (graphql-upload with Express):**
37
- ```typescript
38
- import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs'
39
- app.use(graphqlUploadExpress())
40
- ```
17
+ The `uploadProcess` API keeps the existing buffered calling contract and continues to expose file sizes as numbers. It waits for native `request.formData()` to consume the body, then starts resolver execution once the uploads have been received and prepared. Files can be read from the received `Blob` objects multiple times. The configured size and count limits are checked after body parsing, and the runtime manages the received file storage.
41
18
 
42
- **After (graphql-upload-nextjs with App Router):**
43
- ```typescript
44
- import { GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
19
+ The `uploadProcessStreaming` API is opt-in. It uses [Busboy](https://github.com/mscdex/busboy) to parse `request.body` incrementally, so resolver execution can start as soon as the `operations` and `map` fields have been validated. Each file can be read from private temporary storage whilst the upload is still in progress. Its `fileSize` property is a `Promise<number>`. Limits are enforced during reception, and the API requires a writable `os.tmpdir()` directory.
45
20
 
46
- // In your route handler:
47
- if (request.headers.get("content-type")?.includes("multipart/form-data")) {
48
- return await uploadProcess(request, context, server);
49
- }
50
- ```
21
+ Buffering is a perfectly legitimate option for small uploads when your upstream server enforces a suitable total request-body limit. Streaming is useful for larger uploads, concurrent traffic and processing files as you receive them. Next.js does provide access to a raw request-body stream, so buffering is an implementation choice rather than an inevitable App Router limitation.
51
22
 
52
- Resolver code stays the same — `filename`, `mimetype`, `encoding`, and `createReadStream` work identically.
53
-
54
- ## Usage
55
-
56
- ### Schema and Resolvers
57
-
58
- ```typescript
59
- import path from 'node:path'
60
- import { randomUUID } from 'node:crypto'
61
- import { createWriteStream } from 'node:fs'
62
- import { pipeline } from 'node:stream'
63
- import { gql } from '@apollo/client' // Optional: syntax highlighting only.
64
- import { ApolloServer } from '@apollo/server'
65
- import { startServerAndCreateNextHandler } from '@as-integrations/next'
66
- import { type File, GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
67
- import type { NextRequest } from 'next/server.js'
68
-
69
- const typeDefs = gql`
70
- scalar Upload
71
- type File {
72
- encoding: String!
73
- filename: String!
74
- fileSize: Int!
75
- mimetype: String!
76
- uri: String!
77
- }
78
- type Query {
79
- default: Boolean!
80
- }
81
- type Mutation {
82
- uploadFile(file: Upload!): File!
83
- uploadFiles(files: [Upload!]!): [File!]!
84
- }
85
- `
86
-
87
- interface FileResponse {
88
- encoding: string;
89
- filename: string;
90
- fileSize: number;
91
- mimetype: string;
92
- uri: string;
93
- }
94
-
95
- const resolvers = {
96
- Mutation: {
97
- uploadFile: async (
98
- _parent: undefined,
99
- { file }: { file: Promise<File> },
100
- ): Promise<FileResponse> => {
101
- const { createReadStream, encoding, filename, fileSize, mimetype } = await file;
102
- const safeName = path.basename(filename);
103
- const storedName = randomUUID();
104
- return new Promise((resolve, reject) => {
105
- pipeline(
106
- createReadStream(),
107
- createWriteStream(`./uploads/${storedName}`, { flags: "wx" }),
108
- (error) => {
109
- if (error) reject(new Error("Error during file upload."));
110
- else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${storedName}` });
111
- },
112
- );
113
- });
114
- },
115
- uploadFiles: async (
116
- _parent: undefined,
117
- { files }: { files: Promise<File>[] },
118
- ): Promise<FileResponse[]> => {
119
- const resolvedFiles = await Promise.all(files);
120
- return Promise.all(resolvedFiles.map(async ({ createReadStream, encoding, filename, fileSize, mimetype }) => {
121
- const safeName = path.basename(filename);
122
- const storedName = randomUUID();
123
- return new Promise<FileResponse>((resolve, reject) => {
124
- pipeline(
125
- createReadStream(),
126
- createWriteStream(`./uploads/${storedName}`, { flags: "wx" }),
127
- (error) => {
128
- if (error) reject(new Error(`Error during upload of ${safeName}.`));
129
- else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${storedName}` });
130
- },
131
- );
132
- });
133
- }));
134
- },
135
- },
136
- Query: { default: async () => true },
137
- Upload: GraphQLUpload,
138
- }
139
- ```
23
+ Both APIs support individual files, nested variable paths, file lists, operation batching, deduplication, `operationName` and the same `GraphQLUpload` scalar. MIME detection looks at up to 4,100 bytes and ignores the MIME type provided by the client. Unrecognised binary contents fall back to `application/octet-stream`, and text-like contents to `text/plain`. The detection is heuristic: it doesn't guarantee that a file is safe or well formed.
140
24
 
141
- > **Security:** Always sanitize filenames with `path.basename()` to prevent path traversal attacks. Never write uploaded files to publicly accessible directories in production.
25
+ ## Buffered uploads and existing usage
142
26
 
143
- ### Route Handler
27
+ Existing consumers can keep their imports, handler calls, resolver types and numeric `fileSize` values. Define `scalar Upload` in the GraphQL schema and register `Upload: GraphQLUpload` in the resolvers. Valid buffered requests retain their behaviour; the stricter handling of malformed or ambiguous inputs is described under [Public API compatibility](#public-api-compatibility).
144
28
 
145
- ```typescript
146
- const server = new ApolloServer({ resolvers, typeDefs });
29
+ In a Next.js route, create an `ApolloServer` instance with your app's schema and resolvers. Create a context function using the `NextRequest`, then initialise the Apollo handler with `startServerAndCreateNextHandler`. In the `POST` handler, pass multipart requests, the resolved context, the server and any settings to `uploadProcess`. Otherwise, pass the request to the normal Apollo handler.
147
30
 
148
- const handler = startServerAndCreateNextHandler<NextRequest>(server, {
149
- context: async (req: NextRequest) => ({
150
- ip: req.headers.get("x-forwarded-for") || "",
151
- req,
152
- }),
153
- });
31
+ For instance, you might allow `image/jpeg`, `image/png` and `text/plain`, set `maxFileSize` to 10 MiB and `maxFiles` to 10. The [buffered example route](examples/example-graphql-upload-nextjs/src/app/api/graphql/route.ts) shows the handler, and the [shared schema and resolvers](examples/example-graphql-upload-nextjs/src/lib/graphql.ts) show the integration.
154
32
 
155
- const requestHandler = async (request: NextRequest) => {
156
- if (request.headers.get("content-type")?.includes("multipart/form-data")) {
157
- const context = { ip: request.headers.get("x-forwarded-for") || "", req: request };
158
- return await uploadProcess(request, context, server);
159
- }
160
- return handler(request);
161
- };
33
+ In a buffered resolver, `await file` gives you a `File` with `filename`, `encoding`, `mimetype`, a numeric `fileSize` and `createReadStream()`. Await the full stream pipeline before returning from the resolver.
162
34
 
163
- export const GET = requestHandler;
164
- export const POST = requestHandler;
165
- export const OPTIONS = requestHandler;
166
- ```
35
+ ### Buffered settings
167
36
 
168
- ### Configuration
37
+ - `allowedTypes` defaults to unrestricted. It accepts an array of non-empty MIME strings and compares them against the detected MIME type. An empty array allows no mapped file types.
38
+ - `maxFileSize` defaults to unrestricted and accepts a finite, non-negative byte limit.
39
+ - `maxFiles` defaults to unrestricted and accepts a non-negative safe integer. It limits the number of mapped file entries and the number of physical file parts separately; those counts aren't added together. Unmapped file parts still count towards the physical-file limit.
169
40
 
170
- ```typescript
171
- await uploadProcess(request, context, server, {
172
- allowedTypes: ["image/jpeg", "image/png", "text/plain"],
173
- maxFileSize: 10 * 1024 * 1024, // 10MB
174
- maxFiles: 10,
175
- });
176
- ```
41
+ **These settings don't cap the resources consumed by `request.formData()`.** You'll need an enforced body-size limit before the handler, along with request timeouts and concurrency limits appropriate to your host. Simply checking `Content-Length` won't enforce a limit for streamed requests or a dishonest client.
177
42
 
178
- | Option | Type | Default | Description |
179
- |---|---|---|---|
180
- | `allowedTypes` | `string[]` | `undefined` | Restrict MIME types. Checked against the detected MIME type; unknown binary files are `application/octet-stream`. |
181
- | `maxFileSize` | `number` | `undefined` | Max file size in bytes. Must be finite and non-negative. Returns 413 if exceeded. |
182
- | `maxFiles` | `number` | `undefined` | Max files per request, including unmapped files. Must be a non-negative safe integer. Returns 413 if exceeded. |
43
+ ## Opt-in streaming
183
44
 
184
- ### Client Usage
45
+ Use `uploadProcessStreaming` only on endpoints whose resolvers follow the streaming contract. Existing buffered endpoints won't automatically switch over.
185
46
 
186
- Multipart requests must send `Apollo-Require-Preflight: true` (or a non-empty `X-Apollo-Operation-Name` header). Configure your upload link with `headers: { "Apollo-Require-Preflight": "true" }`. This forces browser preflight and protects the direct execution path from cross-site form submissions. Only allow trusted origins in your CORS policy.
47
+ In a streaming Next.js route, set `export const runtime = 'nodejs'` and pass the request, resolved context, server and streaming settings to `uploadProcessStreaming`. For instance, you might allow `image/jpeg`, `image/png` and `text/plain`, with `maxFieldSize` of 1 MiB, `maxFileSize` of 10 MiB, `maxFiles` of 10 and `maxRequestSize` of 100 MiB. See the [streaming example route](examples/example-graphql-upload-nextjs/src/app/api/graphql-streaming/route.ts).
187
48
 
188
- Map paths must target existing `null` placeholders inside operation variables. Single and batched requests preserve `operationName`.
49
+ The request must expose an unread, unlocked `body` stream and a multipart `Content-Type`. Native Next.js requests also provide an abort `signal` so the library can cancel work when a disconnect is reported. Adapters that only expose `formData()` should continue using the buffered API.
189
50
 
190
- When using a GraphQL client library ([apollo-upload-client](https://npm.im/apollo-upload-client), [urql](https://npm.im/@urql/exchange-multipart-fetch), [extract-files](https://npm.im/extract-files)), file uploads are constructed automatically per the spec.
51
+ ### Streaming resolver contract
191
52
 
192
- ```typescript
193
- import { gql, useMutation } from '@apollo/client';
53
+ The resolver receives a `Promise<StreamingFile>`. Await it to get the upload, then pass `upload.createReadStream()` and your app's writable destination to Node.js's stream pipeline. Await the pipeline, then `upload.fileSize` for the final byte count. You can then return the filename, file size and MIME type.
194
54
 
195
- const UPLOAD = gql`
196
- mutation UploadFile($file: Upload!) {
197
- uploadFile(file: $file) { filename mimetype fileSize }
198
- }
199
- `;
55
+ The destination must be an application-owned writable stream. The [runnable storage example](examples/example-graphql-upload-nextjs/src/lib/storeUpload.ts) uses random identifiers with MIME-based extensions and exclusive writes. If writing or processing that file fails, it attempts to remove that destination. It doesn't roll back other files that have already been stored successfully.
200
56
 
201
- function Uploader() {
202
- const [upload] = useMutation(UPLOAD);
203
- return <input type="file" onChange={(e) => {
204
- const file = e.target.files?.[0];
205
- if (file) upload({ variables: { file } });
206
- }} />;
207
- }
208
- ```
57
+ A few details matter when writing a streaming resolver:
209
58
 
210
- ## API Reference
59
+ - The upload promise resolves once the bounded MIME detection prefix is available. Small files may already have finished reception by then.
60
+ - Each call to `createReadStream()` starts at byte zero and reads independently, even when one physical file is mapped to several variables or batch operations.
61
+ - The `fileSize` promise resolves once the full file has been received and written to temporary storage. Reception failure or cancellation rejects it if it hasn't already settled.
62
+ - Create and finish all readers during resolver execution. Cleanup closes outstanding readers, and new streams are rejected once handler cleanup has started. On normal completion, temporary storage is released before the handler returns.
63
+ - Calling `upload.abort()` cancels the **entire multipart request**, including other uploads and aliases. Destroying an individual reader only stops that reader.
211
64
 
212
- ### Core Exports
65
+ GraphQL execution can start before later file parts have been validated. A late limit violation, malformed part or disconnect can't roll back database changes or other external side effects. Your app has to deal with partial writes and define its own commit/rollback policy.
213
66
 
214
- | Export | Type | Description |
215
- |---|---|---|
216
- | `GraphQLUpload` | `GraphQLScalarType` | The `Upload` scalar for your GraphQL schema. |
217
- | `uploadProcess` | `function` | Processes a multipart request with file uploads. |
218
- | `Upload` | `class` | Holds a promise that resolves with file upload details. |
67
+ Successful responses wait for reception, file writes and MIME validation to finish. The API streams incoming files but keeps the existing JSON response envelope. Apollo incremental results are accumulated into that envelope rather than streamed over HTTP.
219
68
 
220
- ### File Object
69
+ ### Streaming settings
221
70
 
222
- The resolved file object passed to resolvers:
71
+ - `allowedTypes` defaults to unrestricted and uses the same detected MIME allow-list as the buffered API.
72
+ - `maxFieldSize` defaults to 1 MiB and applies separately to each `operations` or `map` field.
73
+ - `maxFileSize` defaults to 10 MiB and applies to every received file, including unmapped files.
74
+ - `maxFiles` defaults to 10. It separately limits mapped entries and received physical file parts, as in the buffered API.
75
+ - `maxRequestSize` defaults to 100 MiB and caps actual received body bytes, including fields, multipart framing and ignored parts.
223
76
 
224
- | Property | Type | Description |
225
- |---|---|---|
226
- | `createReadStream` | `() => ReadableStream` | Creates a Node.js readable stream of the file contents. Replayable. |
227
- | `encoding` | `string` | Transfer encoding (always `'binary'` with FormData API). |
228
- | `filename` | `string` | Original file name from the client. |
229
- | `fileSize` | `number` | File size in bytes. |
230
- | `mimetype` | `string` | MIME type verified via magic bytes. |
77
+ All numeric streaming limits are inclusive, non-negative safe integers. A limit of zero allows zero bytes or files; it doesn't disable the limit. MiB means 1,048,576 bytes.
231
78
 
232
- ### Utility Exports
79
+ The host still needs sufficient disk space, request timeouts, concurrency controls and process-crash recovery. A reverse proxy or hosting platform may buffer a request before the handler sees it, or delay an early error response until the client finishes sending, so check the full deployment path. This implementation requires Node.js and writable temporary storage; it doesn't support the Edge runtime.
233
80
 
234
- | Export | Type | Description |
235
- |---|---|---|
236
- | `bufferToStream` | `(buffer: Buffer) => ReadableStream` | Converts a Buffer to a Node.js readable stream. |
237
- | `parseOperationsJSON` | `(input: string) => object \| object[]` | Parses the operations field (object or array for batching). |
238
- | `sanitizeAndValidateJSON` | `(input: string) => object` | Parses JSON and validates it's a non-null, non-array object. |
239
- | `setValueAtPath` | `(obj, path, value) => void` | Sets a value at a dot-notation path in a nested object. |
240
- | `streamToBuffer` | `(stream: ReadableStream) => Promise<Buffer>` | Collects a readable stream into a Buffer. |
241
- | `validateMap` | `(map: object) => string \| null` | Validates map entries are arrays of string paths. Returns error or null. |
81
+ ## Client requests and security
242
82
 
243
- ### TypeScript Interfaces
83
+ Both upload APIs require a non-empty `Apollo-Require-Preflight` or `X-Apollo-Operation-Name` header before reading the body. Set this header on your upload client:
244
84
 
245
- | Export | Description |
246
- |---|---|
247
- | `File` | Resolved file object with `filename`, `mimetype`, `encoding`, `fileSize`, `createReadStream`. |
248
- | `FileStream` | FormData file entry with a `stream()` method. |
249
- | `FormDataFile` | Raw file entry from multipart FormData. |
250
- | `MinimalRequest` | Request interface compatible with Next.js and Web API. |
251
-
252
- ## Spec Compliance
85
+ ```ts
86
+ headers: { 'Apollo-Require-Preflight': 'true' }
87
+ ```
253
88
 
254
- Implements the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) by [jaydenseric](https://github.com/jaydenseric).
89
+ Use an upload-aware GraphQL transport such as [apollo-upload-client](https://github.com/jaydenseric/apollo-upload-client). Keep your CORS allow-list restricted to origins you trust. The preflight requirement isn't authentication; authentication, authorisation and quotas remain your app's responsibility. Apply the same auth and context policies to JSON and multipart routes. Direct Apollo execution doesn't invoke a separate HTTP adapter's context callback.
255
90
 
256
- The spec defines a [multipart form field structure](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure) with three ordered fields (`operations`, `map`, file fields) and enables nesting files anywhere within operations, operation batching, file deduplication, and file upload streams in resolvers.
91
+ Map paths must point to existing `null` placeholders within operation variables. For batched requests, each path starts with the operation index. A single physical file can map to several paths, but different file fields can't compete for the same placeholder. The parser rejects dangerous prototype keys in paths, duplicate physical file field names and duplicate control fields. Identical file contents are allowed. Missing files reject their associated upload promises.
257
92
 
258
- ### Supported Capabilities
93
+ The streaming parser requires `operations` first, then `map`, then uniquely named file fields. It rejects extra control fields. The buffered API retains its more flexible field-order handling, though clients following the multipart specification should always use the specified order. `FormData.entries()` exposes entry order, so buffered ordering validation is possible; strict ordering is deliberately confined to the opt-in parser for backwards compatibility.
259
94
 
260
- | Spec Capability | Status | Details |
261
- |---|---|---|
262
- | `operations` field ([JSON-encoded GraphQL operation](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure)) | Supported | Parsed and validated as object or array. |
263
- | `map` field ([file-to-path mapping](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure)) | Supported | Validated: each entry must be an array of string paths. |
264
- | [Single file upload](https://github.com/jaydenseric/graphql-multipart-request-spec#single-file) | Supported | File mapped via `"variables.file"` path. |
265
- | [File list upload](https://github.com/jaydenseric/graphql-multipart-request-spec#file-list) | Supported | Files mapped via `"variables.files.0"`, `"variables.files.1"`, etc. |
266
- | [Batching](https://github.com/jaydenseric/graphql-multipart-request-spec#batching) | Supported | Operations as array, paths prefixed with operation index (`"0.variables.file"`). |
267
- | File deduplication | Supported | One file field mapped to multiple operation paths. |
268
- | [`object-path`](https://npm.im/object-path) dot-notation | Supported | Handles nested objects and array indices. |
269
- | File upload streams in resolvers | Supported | `createReadStream()` returns a Node.js readable stream. |
270
- | Missing file → rejected promise | Supported | Upload promise rejected with `"File missing in the request."` |
271
- | `maxFiles` / `maxFileSize` limits | Supported | Returns HTTP 413 when exceeded. |
95
+ Malformed requests return 400, and configured size or count limit violations return 413. Streaming disconnects return 499 when a response can still be delivered. GraphQL execution errors keep Apollo's result envelope. Unexpected exceptions caught during upload processing return a generic 500 without exposing the exception details.
272
96
 
273
- ### Additions Beyond the Spec
97
+ Store uploaded files outside public directories, sanitise display filenames and use server-generated storage keys. MIME sniffing isn't malware scanning or authorisation. The example download endpoint is for development: add authentication and ownership checks before serving private uploads in production.
274
98
 
275
- | Feature | Description |
276
- |---|---|
277
- | MIME magic byte verification | Real file type detected via [file-type](https://npm.im/file-type), not trusting client-provided `Content-Type`. |
278
- | `allowedTypes` filtering | Server-side restriction of accepted MIME types. |
279
- | Unknown binary fallback | Files with no recognized magic bytes and non-text contents are reported as `application/octet-stream`. |
280
- | `fileSize` property | File size in bytes available on the resolved file object. |
99
+ ## Public API compatibility
281
100
 
282
- ### Limitations
101
+ The existing exports are still there: `File`, `FileStream`, `FormDataFile`, `MinimalRequest`, `GraphQLUpload`, `Upload`, `uploadProcess`, `bufferToStream`, `parseOperationsJSON`, `sanitizeAndValidateJSON`, `setValueAtPath`, `streamToBuffer` and `validateMap`. `Upload` now accepts an optional file type parameter; its default is still `File`.
283
102
 
284
- These are inherent trade-offs of using the Web `FormData` API for Next.js App Router compatibility. They do not affect normal spec usage.
103
+ The new exports are `StreamingFile`, `StreamingRequest`, `StreamingUploadSettings` and `uploadProcessStreaming`. Existing buffered callers don't need these new types. Valid buffered requests retain their behaviour. Ambiguous duplicate inputs are now rejected, numeric JSON object keys preserve their sibling properties, malformed body syntax produces a client error, and unexpected server exception details are no longer exposed.
285
104
 
286
- | Limitation | Reason |
287
- |---|---|
288
- | **No field ordering validation** | The [spec requires](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure) `operations` → `map` → files ordering. The Web `FormData` API retrieves fields by name (`formData.get('operations')`), not by position, so ordering cannot be validated. In practice, all major client libraries ([apollo-upload-client](https://npm.im/apollo-upload-client), [extract-files](https://npm.im/extract-files)) send fields in the correct order. |
289
- | **No `maxFieldSize`** | The original [graphql-upload](https://github.com/jaydenseric/graphql-upload) limits non-file field sizes via `busboy`. Next.js parses the full request body into `FormData` before our code runs, so field size limiting is not possible at this layer. |
290
- | **`encoding` is always `'binary'`** | `FormData` does not expose the transfer encoding of file parts. The original `graphql-upload` reads this from `busboy`'s stream events. In practice, transfer encoding is rarely used by resolvers. |
291
- | **No mid-stream abort** | The original uses `fs-capacitor` to buffer uploads to disk, allowing resolvers to abort an in-progress upload. With `FormData`, the entire request body is already parsed by the runtime. However, resolvers can still choose not to call `createReadStream()` to skip processing. |
292
- | **`Blob.stream()` instead of `busboy` streaming** | Next.js route handlers receive a `Request` object (Web API), not a Node.js `IncomingMessage`. There is no access to the raw request stream. `Blob.stream()` provides a replayable readable stream per file. |
105
+ ## Examples and verification
293
106
 
294
- ## Example
107
+ The [example project](examples/example-graphql-upload-nextjs/) has two endpoints: `/api/graphql` takes buffered uploads, and `/api/graphql-streaming` takes streamed ones. Both share the same schema and storage implementation.
295
108
 
296
- A full example project is available at [`examples/example-graphql-upload-nextjs/`](examples/example-graphql-upload-nextjs/).
109
+ From the repository root, build and check the package:
297
110
 
298
- ## Contributing
111
+ ```sh
112
+ npm ci
113
+ npm run build
114
+ npm test
115
+ npm run test:types
116
+ ```
299
117
 
300
- Contributions are welcome! To get started:
118
+ Then build and check the example, return to the root and run the production HTTP tests:
301
119
 
302
- ```bash
303
- git clone https://github.com/lafittemehdy/graphql-upload-nextjs.git
304
- cd graphql-upload-nextjs
305
- npm install
120
+ ```sh
121
+ cd examples/example-graphql-upload-nextjs
122
+ npm ci
306
123
  npm run build
307
- npm test
124
+ npm run lint
125
+ cd ../..
126
+ npm run test:integration
308
127
  ```
309
128
 
310
- CI runs automatically on push and pull requests via GitHub Actions (build + test on Node.js 22/24, example build + lint).
129
+ `npm test` runs unit and integration tests using real Web Requests and Apollo. They cover early reads before upload completion, exact byte boundaries, batching, deduplication, malformed inputs, cancellation, temporary-storage failures and cleanup.
130
+
131
+ `npm run test:types` compiles the legacy consumer contracts against the package's generated declarations. `npm run test:integration` launches a temporary Next.js production server, checks both endpoints and downloads, proves early destination writes over HTTP and verifies cleanup on disconnect. It then stops its test server. CI runs package tests on Node.js 22, 24 and 26, and the production example checks on Node.js 24.
311
132
 
312
- Please read [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) before opening a pull request.
133
+ ### Known verification limits
313
134
 
314
- ## Security
135
+ For synthetic server requests, encode client `FormData` first or provide an explicit byte stream. Node.js 24.22.1's bundled native `FormData` encoder can emit an unhandled error if its generated body is cancelled, reproducible without this package. That reproducer uses a synthetic outgoing body, whereas incoming Next.js HTTP bodies are covered by the production tests. The test runner still treats unhandled errors as failures.
315
136
 
316
- Please read [SECURITY.md](SECURITY.md) before reporting security-sensitive issues.
137
+ The source build type-checks the package's TypeScript. The consumer type check verifies the generated public API with `skipLibCheck` enabled, matching the example's Next.js configuration. A full transitive declaration check currently reports errors in Next.js's bundled declarations and missing ambient React types. Those errors also reproduce when importing `next/server.js` alone, so that check isn't claimed to pass.
317
138
 
318
- ## License
139
+ For further project information, see [CONTRIBUTING.md](CONTRIBUTING.md), [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) and [SECURITY.md](SECURITY.md).
319
140
 
320
- MIT. See [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE).
141
+ ## Licence and acknowledgements
321
142
 
322
- ## Acknowledgements
143
+ This project is licensed under the MIT Licence. See [LICENSE](LICENSE) for the licence text.
323
144
 
324
- Sincere gratitude to [jaydenseric](https://github.com/jaydenseric) for the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) and [graphql-upload](https://github.com/jaydenseric/graphql-upload), and to [meabed](https://github.com/meabed) for [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts) which served as a valuable reference.
145
+ Thanks to [jaydenseric](https://github.com/jaydenseric) for the GraphQL multipart request spec and [graphql-upload](https://github.com/jaydenseric/graphql-upload), which uses Busboy and fs-capacitor for its streaming architecture. Thanks also to [meabed](https://github.com/meabed) for [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts), a very useful reference.
325
146
 
326
- Finally, heartfelt gratitude to my mom for her unwavering support, which has allowed me to dedicate my time to working on open-source software.
147
+ Finally, a very sincere thanks to my Mum for her ongoing support, which has enabled me to devote my time to open source.
package/SECURITY.md CHANGED
@@ -6,8 +6,8 @@ We provide security fixes exclusively for the latest major version.
6
6
 
7
7
  | Version | Supported |
8
8
  | --- | --- |
9
- | 2.x | Yes |
10
- | < 2.0 | No |
9
+ | 3.x | Yes |
10
+ | < 3.0 | No |
11
11
 
12
12
  ## Reporting a Vulnerability
13
13
 
@@ -22,4 +22,4 @@ Please include:
22
22
  * Safe steps to reproduce the issue, if they can be shared securely.
23
23
  * Any known temporary workarounds.
24
24
 
25
- We review valid reports promptly to coordinate fixes and issue security releases.
25
+ We review valid reports promptly to coordinate fixes and issue security releases.
package/core.d.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { GraphQLScalarType } from 'graphql';
2
+ import { NextResponse } from 'next/server.js';
3
+ /** Represents a processed file with metadata and stream access. */
4
+ export interface File {
5
+ createReadStream: () => NodeJS.ReadableStream;
6
+ encoding: string;
7
+ fileSize: number;
8
+ filename: string;
9
+ mimetype: string;
10
+ }
11
+ /** Raw file entry extracted from multipart FormData. */
12
+ export interface FormDataFile {
13
+ lastModified: number;
14
+ name: string;
15
+ size: number;
16
+ type: string;
17
+ }
18
+ /** Extends FormDataFile with a stream method for reading file contents. */
19
+ export interface FileStream extends FormDataFile {
20
+ stream: () => ReadableStream;
21
+ }
22
+ /** Minimal request interface compatible with Next.js and Web API requests. */
23
+ export interface MinimalRequest {
24
+ formData: () => Promise<FormData>;
25
+ headers: {
26
+ get: (name: string) => string | null;
27
+ };
28
+ }
29
+ /** Parameters for Apollo Server's executeOperation method. */
30
+ interface ServerExecuteOperationParams {
31
+ operationName?: string;
32
+ query: string;
33
+ variables: Record<string, unknown>;
34
+ }
35
+ /** Minimal response shape consumed from Apollo Server executeOperation. */
36
+ interface ServerExecuteOperationResponse {
37
+ body: {
38
+ kind: string;
39
+ [key: string]: unknown;
40
+ };
41
+ }
42
+ /** Normalized GraphQL operation shape passed to Apollo Server. */
43
+ export interface Operation {
44
+ operationName?: string;
45
+ query: string;
46
+ variables?: Record<string, unknown>;
47
+ }
48
+ /** Optional upload processing limits and MIME allow-list. */
49
+ export interface UploadProcessSettings {
50
+ allowedTypes?: string[];
51
+ maxFileSize?: number;
52
+ maxFiles?: number;
53
+ }
54
+ /**
55
+ * Represents an instance of a file upload.
56
+ * Holds a promise that resolves with the file details once processed.
57
+ */
58
+ export declare class Upload<TFile = File> {
59
+ file?: TFile;
60
+ promise: Promise<TFile>;
61
+ reject: (reason?: Error | string) => void;
62
+ resolve: (file: TFile) => void;
63
+ constructor();
64
+ }
65
+ /** Custom GraphQL scalar type for handling file uploads. */
66
+ export declare const GraphQLUpload: GraphQLScalarType<Promise<File>, never>;
67
+ /** Converts a Buffer into a Node.js readable stream. */
68
+ export declare function bufferToStream(buffer: Buffer): NodeJS.ReadableStream;
69
+ /** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
70
+ export declare function parseOperationsJSON(input: string): Record<string, unknown> | Record<string, unknown>[];
71
+ /**
72
+ * Processes a file from FormData, detects its MIME type via magic bytes,
73
+ * and returns buffered file metadata with replayable stream access.
74
+ */
75
+ export declare function processUpload(file: FormDataFile, allowedTypes?: string[]): Promise<File>;
76
+ /** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
77
+ export declare function sanitizeAndValidateJSON(input: string): unknown;
78
+ /** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
79
+ export declare function setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): void;
80
+ /** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
81
+ export declare function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer>;
82
+ /** Validates that each map entry is an array of string paths. */
83
+ export declare function validateMap(map: Record<string, unknown>): string | null;
84
+ /** Identifies a bounded file prefix without trusting its name or declared content type. */
85
+ export declare function detectMimeType(headerBuffer: Buffer, allowedTypes?: string[]): Promise<string>;
86
+ /** Distinguishes safe protocol errors from unexpected server exceptions. */
87
+ export declare class UploadRequestError extends Error {
88
+ readonly status: number;
89
+ constructor(message: string, status?: number);
90
+ }
91
+ export interface UploadServer<TContext> {
92
+ executeOperation: (params: ServerExecuteOperationParams, context: {
93
+ contextValue: TContext;
94
+ }) => Promise<ServerExecuteOperationResponse>;
95
+ }
96
+ /** Checks configuration and the preflight boundary before consuming request bytes. */
97
+ export declare function checkUploadRequest(headers: MinimalRequest['headers'], settings?: UploadProcessSettings): void;
98
+ /** Validates every target before replacing nulls; assignment preserves existing container shapes. */
99
+ export declare function prepareOperations<TFile = File>(operationsRaw: string, mapRaw: string, maxFiles?: number): {
100
+ operations: Operation | Operation[];
101
+ uploads: Map<string, Upload<TFile>>;
102
+ };
103
+ /** Preserves operation order, context, and the existing response envelope in both APIs. */
104
+ export declare function executeOperations<TContext>(operations: Operation | Operation[], context: TContext, server: UploadServer<TContext>): Promise<NextResponse>;
105
+ /** Only intentional request errors may expose their details to an untrusted client. */
106
+ export declare function uploadErrorResponse(error: unknown): NextResponse;
107
+ export {};