GraphQL Yoga supports the GraphQL Multipart Request Specification, allowing you to upload files and consume the binary data inside GraphQL Resolvers via HTTP.
GraphQL Yoga supports the
GraphQL Multipart Request Specification,
allowing you to upload files and consume the binary data inside GraphQL Resolvers via HTTP.
If you want to disable multipart request processing for some reason, you can pass multipart: false
to prevent Yoga from handling multipart requests.
createYoga({ multipart: false })
Configuring Multipart Request Processing (only for Node.js)
In Node.js, you can configure the limits of the multipart request processing such as maximum allowed
file size, maximum numbers of files, etc.
Fetch API’s Request.formData method doesn’t have any options to configure the limits of Multipart
request processing. Instead we can configure our Fetch API ponyfill to manage that.
import { createYoga } from 'graphql-yoga'import { createFetch } from '@whatwg-node/fetch'createYoga({ fetchAPI: createFetch({ formDataLimits: { // Maximum allowed file size (in bytes) fileSize: 1000000, // Maximum allowed number of files files: 10, // Maximum allowed size of content (operations, variables etc...) fieldSize: 1000000, // Maximum allowed header size for form data headerSize: 1000000 } })})
Third Party Integrations
Usage with S3
Amazon S3 is a popular object storage service. You can use GraphQL Yoga to upload files to S3. In
this example, we will use the
AWS SDK for JavaScript v3.
Note that S3 is a common protocol and you can use other storage providers than AWS.
file-upload-example.ts
import { createServer } from 'http'import { createYoga } from 'graphql-yoga'import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'const client = new S3Client({})// Provide your schemaconst yoga = createYoga({ schema: createSchema({ typeDefs: /* GraphQL */ ` scalar File type Mutation { upload(file: File!): Boolean! } `, resolvers: { Mutation: { upload: async (_, { file }: { file: File }) => { try { await client.send( new PutObjectCommand({ Bucket: 'test-bucket', Key: file.name, Body: Buffer.from(await file.arrayBuffer()) }) ) return true } catch (e) { return false } } } } })})// Start the server and explore http://localhost:4000/graphqlconst server = createServer(yoga)server.listen(4000, () => { console.info('Server is running on http://localhost:4000/graphql')})
This site uses cookies for analytics and improving your experience.