graphql-upload-nextjs 1.0.0 → 2.0.1

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/README.md CHANGED
@@ -1,364 +1,319 @@
1
- # graphql-upload-nextjs
2
-
3
- `graphql-upload-nextjs` is a robust package that enables seamless file uploads in a Next.js environment using GraphQL. This package is designed to integrate easily with Apollo Server, allowing you to handle file uploads in your GraphQL mutations with ease and efficiency.
4
-
5
- ## Features
6
-
7
- - Supports file uploads via GraphQL in a Next.js environment.
8
- - Utilizes Apollo Server for handling GraphQL operations.
9
- - Provides utilities for processing and validating file uploads.
10
- - Handles various file types with customizable MIME type and size restrictions.
11
- - Offers a clear and structured approach for integrating file uploads into your GraphQL schema.
12
-
13
- ## Installation
14
-
15
- To install the package, use one of the following commands:
16
-
17
- ```bash
18
- npm install graphql-upload-nextjs
19
- # or
20
- yarn add graphql-upload-nextjs
21
- # or
22
- pnpm add graphql-upload-nextjs
23
- ```
24
-
25
- ## Usage
26
-
27
- ### Importing the Package
28
-
29
- Import the necessary components from the package:
30
-
31
- ```javascript
32
- import { GraphQLUpload, type File, uploadProcess } from 'graphql-upload-nextjs'
33
-
34
- import { ApolloServer } from '@apollo/server'
35
- import { NextRequest } from 'next/server'
36
- import { createWriteStream } from 'fs'
37
- import { pipeline } from 'stream'
38
- import { startServerAndCreateNextHandler } from '@as-integrations/next'
39
-
40
- // Optional: Use the gql module from Apollo Client for syntax highlighting.
41
- // This package is already installed for the client side.
42
- import { gql } from '@apollo/client'
43
- ```
44
-
45
- ### Defining the GraphQL Schema and Resolvers
46
-
47
- Define your GraphQL schema and resolvers:
48
-
49
- ```javascript
50
- // For this example, we define the GraphQL schema and resolvers below.
51
- const typeDefs = gql`
52
- # Custom scalar type for handling file uploads.
53
- scalar Upload
54
- type File {
55
- encoding: String!
56
- fileName: String!
57
- fileSize: Int!
58
- mimeType: String!
59
- uri: String!
60
- }
61
- type Query {
62
- default: Boolean!
63
- }
64
- type Mutation {
65
- uploadFile(file: Upload!): File!
66
- uploadFiles(files: [Upload!]!): [File!]!
67
- }
68
- `
69
-
70
- const resolvers = {
71
- Mutation: {
72
- uploadFile: async (
73
- _parent: undefined,
74
- { file }: { file: Promise<File> },
75
- _context: Context,
76
- ): Promise<GraphQLFileResponse> => {
77
- try {
78
- const { createReadStream, encoding, fileName, fileSize, mimeType } =
79
- await file;
80
- const allowedTypes = ["image/jpeg", "image/png", "text/plain"];
81
- const maxFileSize = 10 * 1024 * 1024; // 10MB
82
-
83
- if (!allowedTypes.includes(mimeType)) {
84
- throw new Error(`File type ${mimeType} is not allowed.`);
85
- }
86
-
87
- if (fileSize > maxFileSize) {
88
- throw new Error(`File size exceeds the limit of 10MB.`);
89
- }
90
-
91
- return new Promise<GraphQLFileResponse>((resolve, reject) => {
92
- pipeline(
93
- createReadStream(),
94
- // IMPORTANT: Storing files in 'public' is insecure for production. Use secure storage.
95
- createWriteStream(`./public/${fileName}`),
96
- (error) => {
97
- if (error) {
98
- reject(new Error("Error during file upload."));
99
- } else {
100
- resolve({
101
- encoding,
102
- fileName,
103
- fileSize,
104
- mimeType,
105
- uri: `http://localhost:3000/${fileName}`,
106
- });
107
- }
108
- },
109
- );
110
- });
111
- } catch (_error) {
112
- throw new Error("Failed to handle file upload.");
113
- }
114
- },
115
- uploadFiles: async (
116
- _parent: undefined,
117
- { files }: { files: Promise<File>[] },
118
- _context: Context,
119
- ): Promise<GraphQLFileResponse[]> => {
120
- const resolvedFileObjects = await Promise.all(files);
121
- const allowedTypes = ["image/jpeg", "image/png", "text/plain"];
122
- const maxFileSize = 10 * 1024 * 1024; // 10MB
123
-
124
- const processingPromises = resolvedFileObjects.map(async (fileObject) => {
125
- if (
126
- !fileObject ||
127
- typeof fileObject.createReadStream !== "function" ||
128
- !fileObject.fileName
129
- ) {
130
- throw new Error(
131
- `Invalid file data encountered for one of the files.`,
132
- );
133
- }
134
-
135
- const { createReadStream, encoding, fileName, fileSize, mimeType } =
136
- fileObject;
137
-
138
- if (!allowedTypes.includes(mimeType)) {
139
- throw new Error(
140
- `File type ${mimeType} is not allowed for ${fileName}.`,
141
- );
142
- }
143
-
144
- if (fileSize > maxFileSize) {
145
- throw new Error(`File ${fileName} size exceeds the limit of 10MB.`);
146
- }
147
-
148
- return new Promise<GraphQLFileResponse>((resolve, reject) => {
149
- const readStream = createReadStream();
150
- if (typeof readStream.pipe !== "function") {
151
- return reject(
152
- new Error(`Failed to get a readable stream for ${fileName}.`),
153
- );
154
- }
155
- pipeline(
156
- readStream,
157
- // IMPORTANT: Insecure storage. Use secure solution in production.
158
- createWriteStream(`./public/${fileName}`),
159
- (error) => {
160
- if (error) {
161
- reject(new Error(`Error during upload of ${fileName}.`));
162
- } else {
163
- resolve({
164
- encoding,
165
- fileName,
166
- fileSize,
167
- mimeType,
168
- uri: `http://localhost:3000/${fileName}`,
169
- });
170
- }
171
- },
172
- );
173
- });
174
- });
175
-
176
- return Promise.all(processingPromises);
177
- },
178
- },
179
- Query: {
180
- default: async () => true
181
- },
182
- // Add the custom scalar type for file uploads.
183
- Upload: GraphQLUpload
184
- }
185
- ```
186
-
187
- ### Creating the Apollo Server
188
-
189
- Create the Apollo Server instance and set up the request handler:
190
-
191
- ```javascript
192
- const server = new ApolloServer({ resolvers, typeDefs });
193
-
194
- interface Context {
195
- ip: string;
196
- req: NextRequest;
197
- [key: string]: unknown;
198
- }
199
-
200
- const contextHandler = async (
201
- req: NextRequest,
202
- authenticated: string | boolean = false,
203
- ): Promise<Context> => {
204
- const ip = req.headers.get("x-forwarded-for") || "";
205
- if (authenticated) return { ip, req };
206
- return { ip, req };
207
- };
208
-
209
- interface ServerExecuteOperationParams {
210
- query: string;
211
- variables: Record<string, unknown>;
212
- }
213
-
214
- interface ExpectedServerType<TContext extends Record<string, unknown>> {
215
- executeOperation: (
216
- params: ServerExecuteOperationParams,
217
- context: { contextValue: TContext },
218
- ) => Promise<GraphQLResponse<TContext>>;
219
- }
220
-
221
- const handler = startServerAndCreateNextHandler<NextRequest, Context>(server, {
222
- context: contextHandler,
223
- });
224
-
225
- const requestHandler = async (request: NextRequest) => {
226
- try {
227
- if (request.headers.get("content-type")?.includes("multipart/form-data")) {
228
- // IMPORTANT: Authenticate before processing uploads. Placeholder 'User' used.
229
- const context = await contextHandler(request, "User");
230
- return await uploadProcess(
231
- request,
232
- context,
233
- server as ExpectedServerType<Context>,
234
- );
235
- }
236
- return handler(request);
237
- } catch (_error) {
238
- throw new Error("Failed to process request.");
239
- }
240
- };
241
-
242
- // Export request handlers for GET, POST, and OPTIONS methods.
243
- export const GET = requestHandler;
244
- export const POST = requestHandler;
245
- export const OPTIONS = requestHandler;
246
- ```
247
-
248
- ### Executing the Mutations
249
-
250
- When sending requests to your GraphQL server, you'll need to structure your mutation and variables correctly. This package adheres to the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) for file uploads.
251
-
252
- **Single File Upload (`uploadFile` mutation):**
253
-
254
- *GraphQL Operation:*
255
- ```graphql
256
- mutation UploadFile($file: Upload!) {
257
- uploadFile(file: $file) {
258
- fileName
259
- mimeType
260
- encoding
261
- uri
262
- fileSize
263
- }
264
- }
265
- ```
266
-
267
- *GraphQL Variables:*
268
- The key in the variables object (`"file"`) must match the argument name in your GraphQL mutation (`$file`).
269
- When using a GraphQL client library (e.g., Apollo Client, urql, Relay):
270
- * You'll typically pass the browser's `File` object (e.g., from an `<input type="file">`) directly as the value for the `file` variable.
271
- * The client library automatically constructs the multipart/form-data request according to the GraphQL multipart request specification.
272
-
273
- The `{"file": null}` structure illustrates how the `operations` part of the multipart request is formed, where `null` acts as a placeholder for the actual file content that is sent in a separate part of the request. You generally don't need to construct this manually when using a client library.
274
-
275
- *Example with a client library (conceptual):*
276
- ```javascript
277
- // In your frontend code
278
- import { gql, useMutation } from '@apollo/client'; // Or your client of choice
279
-
280
- const UPLOAD_FILE_MUTATION = gql`
281
- mutation UploadFile($file: Upload!) {
282
- uploadFile(file: $file) { fileName }
283
- }
284
- `;
285
-
286
- function MyUploader() {
287
- const [uploadFileMutation] = useMutation(UPLOAD_FILE_MUTATION);
288
-
289
- const handleChange = (event) => {
290
- const file = event.target.files[0];
291
- if (file) {
292
- uploadFileMutation({ variables: { file } });
293
- }
294
- };
295
-
296
- return <input type="file" onChange={handleChange} />;
297
- }
298
- ```
299
-
300
- **Multiple File Upload (`uploadFiles` mutation):**
301
-
302
- *GraphQL Operation:*
303
- ```graphql
304
- mutation UploadFiles($files: [Upload!]!) {
305
- uploadFiles(files: $files) {
306
- fileName
307
- mimeType
308
- encoding
309
- uri
310
- fileSize
311
- }
312
- }
313
- ```
314
-
315
- *GraphQL Variables:*
316
- Similarly, the key `"files"` must match the argument name (`$files`).
317
- When using a GraphQL client library:
318
- * You'll pass an array of `File` objects as the value for the `files` variable.
319
- * The client library handles the multipart request construction.
320
-
321
- The `{"files": [null, null]}` structure illustrates the `operations` part, with `null` placeholders for file content sent separately.
322
-
323
- *Example with a client library (conceptual):*
324
- ```javascript
325
- // In your frontend code
326
- const UPLOAD_FILES_MUTATION = gql`
327
- mutation UploadFiles($files: [Upload!]!) {
328
- uploadFiles(files: $files) { fileName }
329
- }
330
- `;
331
-
332
- function MyMultiUploader() {
333
- const [uploadFilesMutation] = useMutation(UPLOAD_FILES_MUTATION);
334
-
335
- const handleChange = (event) => {
336
- const files = Array.from(event.target.files);
337
- if (files.length > 0) {
338
- uploadFilesMutation({ variables: { files } });
339
- }
340
- };
341
-
342
- return <input type="file" multiple onChange={handleChange} />;
343
- }
344
- ```
345
-
346
- ## Example
347
-
348
- An example project demonstrating how to integrate GraphQL file uploads into a typical Next.js starter application is available in the repository under `graphql-upload-nextjs/examples/example-graphql-upload-nextjs/`.
349
-
350
- ## Contributing
351
-
352
- Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.
353
-
354
- ## License
355
-
356
- This project is licensed under the MIT License. See the [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE) file for more information.
357
-
358
- ## Acknowledgements
359
-
360
- I would like to express my sincere gratitude to [meabed](https://github.com/meabed) for their excellent work on [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts), which served as a valuable reference and inspiration for this project. I am also grateful to [jaydenseric](https://github.com/jaydenseric) for developing the original specifications for [graphql-upload](https://github.com/jaydenseric/graphql-upload).
361
-
362
- While this project deviates from the official specifications to prioritize compatibility with Next.js routes, I am committed to refining it further to align with those specifications as closely as possible. Notable enhancements include built-in security features, such as file type verification, as well as support and an example for GraphQL authentication.
363
-
364
- Finally, I would like to extend my heartfelt gratitude to my mom for her unwavering support, which has allowed me to dedicate my time to working on open-source software.
1
+ # graphql-upload-nextjs
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-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`.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install graphql-upload-nextjs
28
+ ```
29
+
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.
33
+
34
+ Property names match the original: `filename`, `mimetype`, `encoding`, `createReadStream`. An additional `fileSize` property is also available.
35
+
36
+ **Before (graphql-upload with Express):**
37
+ ```typescript
38
+ import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs'
39
+ app.use(graphqlUploadExpress())
40
+ ```
41
+
42
+ **After (graphql-upload-nextjs with App Router):**
43
+ ```typescript
44
+ import { GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
45
+
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
+ ```
51
+
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 { createWriteStream } from 'node:fs'
61
+ import { pipeline } from 'node:stream'
62
+ import { gql } from '@apollo/client' // Optional: syntax highlighting only.
63
+ import { ApolloServer } from '@apollo/server'
64
+ import { startServerAndCreateNextHandler } from '@as-integrations/next'
65
+ import { type File, GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
66
+ import type { NextRequest } from 'next/server.js'
67
+
68
+ const typeDefs = gql`
69
+ scalar Upload
70
+ type File {
71
+ encoding: String!
72
+ filename: String!
73
+ fileSize: Int!
74
+ mimetype: String!
75
+ uri: String!
76
+ }
77
+ type Query {
78
+ default: Boolean!
79
+ }
80
+ type Mutation {
81
+ uploadFile(file: Upload!): File!
82
+ uploadFiles(files: [Upload!]!): [File!]!
83
+ }
84
+ `
85
+
86
+ interface FileResponse {
87
+ encoding: string;
88
+ filename: string;
89
+ fileSize: number;
90
+ mimetype: string;
91
+ uri: string;
92
+ }
93
+
94
+ const resolvers = {
95
+ Mutation: {
96
+ uploadFile: async (
97
+ _parent: undefined,
98
+ { file }: { file: Promise<File> },
99
+ ): Promise<FileResponse> => {
100
+ const { createReadStream, encoding, filename, fileSize, mimetype } = await file;
101
+ const safeName = path.basename(filename);
102
+ return new Promise((resolve, reject) => {
103
+ pipeline(
104
+ createReadStream(),
105
+ createWriteStream(`./uploads/${safeName}`),
106
+ (error) => {
107
+ if (error) reject(new Error("Error during file upload."));
108
+ else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${safeName}` });
109
+ },
110
+ );
111
+ });
112
+ },
113
+ uploadFiles: async (
114
+ _parent: undefined,
115
+ { files }: { files: Promise<File>[] },
116
+ ): Promise<FileResponse[]> => {
117
+ const resolvedFiles = await Promise.all(files);
118
+ return Promise.all(resolvedFiles.map(async ({ createReadStream, encoding, filename, fileSize, mimetype }) => {
119
+ const safeName = path.basename(filename);
120
+ return new Promise<FileResponse>((resolve, reject) => {
121
+ pipeline(
122
+ createReadStream(),
123
+ createWriteStream(`./uploads/${safeName}`),
124
+ (error) => {
125
+ if (error) reject(new Error(`Error during upload of ${safeName}.`));
126
+ else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${safeName}` });
127
+ },
128
+ );
129
+ });
130
+ }));
131
+ },
132
+ },
133
+ Query: { default: async () => true },
134
+ Upload: GraphQLUpload,
135
+ }
136
+ ```
137
+
138
+ > **Security:** Always sanitize filenames with `path.basename()` to prevent path traversal attacks. Never write uploaded files to publicly accessible directories in production.
139
+
140
+ ### Route Handler
141
+
142
+ ```typescript
143
+ const server = new ApolloServer({ resolvers, typeDefs });
144
+
145
+ const handler = startServerAndCreateNextHandler<NextRequest>(server, {
146
+ context: async (req: NextRequest) => ({
147
+ ip: req.headers.get("x-forwarded-for") || "",
148
+ req,
149
+ }),
150
+ });
151
+
152
+ const requestHandler = async (request: NextRequest) => {
153
+ if (request.headers.get("content-type")?.includes("multipart/form-data")) {
154
+ const context = { ip: request.headers.get("x-forwarded-for") || "", req: request };
155
+ return await uploadProcess(request, context, server);
156
+ }
157
+ return handler(request);
158
+ };
159
+
160
+ export const GET = requestHandler;
161
+ export const POST = requestHandler;
162
+ export const OPTIONS = requestHandler;
163
+ ```
164
+
165
+ ### Configuration
166
+
167
+ ```typescript
168
+ await uploadProcess(request, context, server, {
169
+ allowedTypes: ["image/jpeg", "image/png", "text/plain"],
170
+ maxFileSize: 10 * 1024 * 1024, // 10MB
171
+ maxFiles: 10,
172
+ });
173
+ ```
174
+
175
+ | Option | Type | Default | Description |
176
+ |---|---|---|---|
177
+ | `allowedTypes` | `string[]` | `undefined` | Restrict MIME types. Checked against the detected MIME type; unknown binary files are `application/octet-stream`. |
178
+ | `maxFileSize` | `number` | `undefined` | Max file size in bytes. Must be finite and non-negative. Returns 413 if exceeded. |
179
+ | `maxFiles` | `number` | `undefined` | Max files per request. Must be finite and non-negative. Returns 413 if exceeded. |
180
+
181
+ ### Client Usage
182
+
183
+ 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.
184
+
185
+ ```typescript
186
+ import { gql, useMutation } from '@apollo/client';
187
+
188
+ const UPLOAD = gql`
189
+ mutation UploadFile($file: Upload!) {
190
+ uploadFile(file: $file) { filename mimetype fileSize }
191
+ }
192
+ `;
193
+
194
+ function Uploader() {
195
+ const [upload] = useMutation(UPLOAD);
196
+ return <input type="file" onChange={(e) => {
197
+ const file = e.target.files?.[0];
198
+ if (file) upload({ variables: { file } });
199
+ }} />;
200
+ }
201
+ ```
202
+
203
+ ## API Reference
204
+
205
+ ### Core Exports
206
+
207
+ | Export | Type | Description |
208
+ |---|---|---|
209
+ | `GraphQLUpload` | `GraphQLScalarType` | The `Upload` scalar for your GraphQL schema. |
210
+ | `uploadProcess` | `function` | Processes a multipart request with file uploads. |
211
+ | `Upload` | `class` | Holds a promise that resolves with file upload details. |
212
+
213
+ ### File Object
214
+
215
+ The resolved file object passed to resolvers:
216
+
217
+ | Property | Type | Description |
218
+ |---|---|---|
219
+ | `createReadStream` | `() => ReadableStream` | Creates a Node.js readable stream of the file contents. Replayable. |
220
+ | `encoding` | `string` | Transfer encoding (always `'binary'` with FormData API). |
221
+ | `filename` | `string` | Original file name from the client. |
222
+ | `fileSize` | `number` | File size in bytes. |
223
+ | `mimetype` | `string` | MIME type verified via magic bytes. |
224
+
225
+ ### Utility Exports
226
+
227
+ | Export | Type | Description |
228
+ |---|---|---|
229
+ | `bufferToStream` | `(buffer: Buffer) => ReadableStream` | Converts a Buffer to a Node.js readable stream. |
230
+ | `parseOperationsJSON` | `(input: string) => object \| object[]` | Parses the operations field (object or array for batching). |
231
+ | `sanitizeAndValidateJSON` | `(input: string) => object` | Parses JSON and validates it's a non-null, non-array object. |
232
+ | `setValueAtPath` | `(obj, path, value) => void` | Sets a value at a dot-notation path in a nested object. |
233
+ | `streamToBuffer` | `(stream: ReadableStream) => Promise<Buffer>` | Collects a readable stream into a Buffer. |
234
+ | `validateMap` | `(map: object) => string \| null` | Validates map entries are arrays of string paths. Returns error or null. |
235
+
236
+ ### TypeScript Interfaces
237
+
238
+ | Export | Description |
239
+ |---|---|
240
+ | `File` | Resolved file object with `filename`, `mimetype`, `encoding`, `fileSize`, `createReadStream`. |
241
+ | `FileStream` | FormData file entry with a `stream()` method. |
242
+ | `FormDataFile` | Raw file entry from multipart FormData. |
243
+ | `MinimalRequest` | Request interface compatible with Next.js and Web API. |
244
+
245
+ ## Spec Compliance
246
+
247
+ Implements the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) by [jaydenseric](https://github.com/jaydenseric).
248
+
249
+ 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.
250
+
251
+ ### Supported Capabilities
252
+
253
+ | Spec Capability | Status | Details |
254
+ |---|---|---|
255
+ | `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. |
256
+ | `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. |
257
+ | [Single file upload](https://github.com/jaydenseric/graphql-multipart-request-spec#single-file) | Supported | File mapped via `"variables.file"` path. |
258
+ | [File list upload](https://github.com/jaydenseric/graphql-multipart-request-spec#file-list) | Supported | Files mapped via `"variables.files.0"`, `"variables.files.1"`, etc. |
259
+ | [Batching](https://github.com/jaydenseric/graphql-multipart-request-spec#batching) | Supported | Operations as array, paths prefixed with operation index (`"0.variables.file"`). |
260
+ | File deduplication | Supported | One file field mapped to multiple operation paths. |
261
+ | [`object-path`](https://npm.im/object-path) dot-notation | Supported | Handles nested objects and array indices. |
262
+ | File upload streams in resolvers | Supported | `createReadStream()` returns a Node.js readable stream. |
263
+ | Missing file → rejected promise | Supported | Upload promise rejected with `"File missing in the request."` |
264
+ | `maxFiles` / `maxFileSize` limits | Supported | Returns HTTP 413 when exceeded. |
265
+
266
+ ### Additions Beyond the Spec
267
+
268
+ | Feature | Description |
269
+ |---|---|
270
+ | MIME magic byte verification | Real file type detected via [file-type](https://npm.im/file-type), not trusting client-provided `Content-Type`. |
271
+ | `allowedTypes` filtering | Server-side restriction of accepted MIME types. |
272
+ | Unknown binary fallback | Files with no recognized magic bytes and non-text contents are reported as `application/octet-stream`. |
273
+ | `fileSize` property | File size in bytes available on the resolved file object. |
274
+
275
+ ### Limitations
276
+
277
+ These are inherent trade-offs of using the Web `FormData` API for Next.js App Router compatibility. They do not affect normal spec usage.
278
+
279
+ | Limitation | Reason |
280
+ |---|---|
281
+ | **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. |
282
+ | **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. |
283
+ | **`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. |
284
+ | **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. |
285
+ | **`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. |
286
+
287
+ ## Example
288
+
289
+ A full example project is available at [`examples/example-graphql-upload-nextjs/`](examples/example-graphql-upload-nextjs/).
290
+
291
+ ## Contributing
292
+
293
+ Contributions are welcome! To get started:
294
+
295
+ ```bash
296
+ git clone https://github.com/lafittemehdy/graphql-upload-nextjs.git
297
+ cd graphql-upload-nextjs
298
+ npm install
299
+ npm run build
300
+ npm test
301
+ ```
302
+
303
+ CI runs automatically on push and pull requests via GitHub Actions (build + test on Node.js 22/24, example build + lint).
304
+
305
+ Please read [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) before opening a pull request.
306
+
307
+ ## Security
308
+
309
+ Please read [SECURITY.md](SECURITY.md) before reporting security-sensitive issues.
310
+
311
+ ## License
312
+
313
+ MIT. See [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE).
314
+
315
+ ## Acknowledgements
316
+
317
+ 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.
318
+
319
+ Finally, heartfelt gratitude to my mom for her unwavering support, which has allowed me to dedicate my time to working on open-source software.