File Upload in GraphQL

GraphQL has no file type because its requests are JSON, and JSON can't carry binary data. Base64 works, but the body grows by a third (1.2 MB becomes 1.6 MB)…

Bookshop staff want to put up the cover of The Dancer, a 1.2 MB JPEG. The mutation is easy to write. The trouble is the file: GraphQL has no type for files. A GraphQL request over HTTP is JSON, and JSON only knows text, numbers, booleans, null, arrays and objects; there's no place for the bytes of an image. So uploading a book cover needs another route.

It's like sending a photo in a letter that may only hold letters. You can, by rewriting the photo as a string of letters (Base64), but the letter gets thick. The sensible way: drop the photo off at the stockroom through the back door, and the letter just carries its shelf number.

Why GraphQL has no file type

The GraphQL spec has only five built-in scalars: Int, Float, String, Boolean and ID. How a request travels is set out separately (GraphQL over HTTP), and its shape is JSON: { "query": "...", "variables": { ... } }. JSON has no type for binary data, so a file must become text, travel in another format, or not go through GraphQL at all. There are three choices.

Base64: possible, but costly

Base64 writes every 3 bytes as 4 characters. The cover goes into a variable as an ordinary string:

mutation SetCover($bookId: ID!, $image: String!) {
  setCoverBase64(bookId: $bookId, image: $image) {
    title
    coverUrl
  }
}

The image variable holds "/9j/4AAQSkZJRgABAQ..." (a JPEG file always starts with /9j/ in Base64). A 1,200,000-byte file becomes 1,600,000 characters, so the request body is 1,600,168 bytes, about 1.6 MB: a third bigger than the file. The GraphQL server must also read that whole string as one JSON value, keep it in memory, decode it, and only then send it to storage. Body limits have a say too: express.json() defaults to only 100 KB, Apollo Server's startStandaloneServer to 50 MB. Base64 is still fine for very small files, such as an icon of a few KB.

Option 1: the GraphQL multipart request

The GraphQL multipart request spec by Jayden Seric sends the operation and the file in one multipart/form-data request, like an ordinary upload form. It has three parts: operations (the query and variables, with the file set to null), map (which file replaces which variable), then the file:

------bookshop
Content-Disposition: form-data; name="operations"

{"query":"mutation ($file: Upload!) { uploadCover(bookId: 4, file: $file) { title coverUrl } }","variables":{"file":null}}
------bookshop
Content-Disposition: form-data; name="map"

{"0":["variables.file"]}
------bookshop
Content-Disposition: form-data; name="0"; filename="the-dancer.jpg"
Content-Type: image/jpeg

(1,200,000 bytes of image)
------bookshop--

On the server, the graphql-upload package (version 17.1.0, which fits Apollo Server 5 and graphql 16; version 18 needs graphql 17 and fails to install beside Apollo Server 5) reads those parts and gives the resolver a scalar Upload:

import graphqlUploadExpress from "graphql-upload/graphqlUploadExpress.mjs";

app.use("/graphql", graphqlUploadExpress({ maxFileSize: 5_000_000, maxFiles: 1 }));

There's one security trap. multipart/form-data is a "simple" content type: a browser will send it from another site without asking first (no CORS preflight). That's a CSRF (Cross-Site Request Forgery) hole: a malicious site can make Sari's browser send a mutation in Sari's name. That's why Apollo Server, since version 4, refuses such a request unless it carries a non-empty Apollo-Require-Preflight or X-Apollo-Operation-Name header. Without one, the answer is status 400:

{
  "errors": [
    {
      "message": "This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight\n",
      "extensions": { "code": "BAD_REQUEST" }
    }
  ]
}

A custom header forces the browser to ask first (a preflight), and another site won't be allowed. So upload clients send Apollo-Require-Preflight: true. Even when it's safe, the file still passes through your GraphQL server, and Apollo's own documentation recommends the next way.

Option 2, the recommended one: a presigned URL

The file doesn't go through the GraphQL server at all. The server only hands out a one-time permission to upload: a presigned URL, an address at the storage (S3 or the like) that is already signed and expires within minutes. The flow has three steps:

# Request Through the GraphQL server (request + response)
1 mutation { createCoverUpload(bookId: 4, contentType: "image/jpeg", size: 1200000) { uploadUrl key expiresAt } } 313 bytes
2 PUT the file to uploadUrl, straight to storage 0 bytes
3 mutation { attachCover(bookId: 4, key: "covers/4-1.jpg") { title coverUrl } } 192 bytes

The answers to steps 1 and 3 from the Bookshop server in the Lab:

{ "data": { "createCoverUpload": { "uploadUrl": "https://storage.bookshop.test/covers/4-1.jpg?X-Amz-Expires=300&X-Amz-Signature=demo", "key": "covers/4-1.jpg", "expiresAt": "2026-10-11T10:05:00Z" } } }
{ "data": { "attachCover": { "title": "The Dancer", "coverUrl": "https://cdn.bookshop.test/covers/4-1.jpg" } } }

The step 1 resolver with the AWS SDK, version 3:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const s3 = new S3Client({});
const MAX_COVER = 5_000_000; // 5 MB

const resolvers = {
  Mutation: {
    createCoverUpload: async (_, { bookId, contentType, size }) => {
      if (!["image/jpeg", "image/png", "image/webp"].includes(contentType)) {
        throw new GraphQLError("Cover must be a JPEG, PNG or WebP image", { extensions: { code: "BAD_USER_INPUT" } });
      }
      if (size > MAX_COVER) {
        throw new GraphQLError("Cover must be 5 MB or smaller", { extensions: { code: "BAD_USER_INPUT" } });
      }
      const key = `covers/${bookId}-${crypto.randomUUID()}.jpg`; // the server picks the key
      const command = new PutObjectCommand({ Bucket: "bookshop-covers", Key: key, ContentType: contentType });
      const uploadUrl = await getSignedUrl(s3, command, { expiresIn: 300 }); // 5 minutes
      return { uploadUrl, key, expiresAt: new Date(Date.now() + 300_000).toISOString() };
    },
  },
};

Step 2 in the browser:

// browser, step 2: the file from <input type="file">
const file = input.files[0];
const res = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": file.type }, body: file });
if (!res.ok) throw new Error(`Upload failed: ${res.status}`);

Size limits

Limits must be kept on the server, because the client's numbers can lie. With a presigned URL, createCoverUpload refuses a size over 5 MB before a single byte is sent, then attachCover checks the real size of the file in storage (with a HEAD request, say). S3 also has presigned POST with a content-length-range condition if you want the storage itself to enforce the limit. With multipart, maxFileSize in graphql-upload cuts off a file that's too big, and reading its stream throws File truncated as it exceeds the 5000000 byte size limit.

⚠️ Uploads that waste memory or let others in

TL;DR: GraphQL has no file type because its requests are JSON, and JSON can't carry binary data. Base64 works, but the body grows by a third (1.2 MB becomes 1.6 MB) and all of it goes through the server. The GraphQL multipart request (Jayden Seric's spec, the graphql-upload package) sends the file as multipart/form-data with an operations part, a map part and the file; Apollo Server refuses it as a potential CSRF unless it has an Apollo-Require-Preflight or X-Apollo-Operation-Name header. The most scalable way is a presigned URL: the createCoverUpload mutation gives an uploadUrl and a key, the client PUTs the file straight to storage, then attachCover joins it to the book. Size limits are kept on the server: before the URL is handed out, and once more on the real file.

⚡ GraphQL has no file type

Guess first: why can't a 1.2 MB cover go straight into an ordinary GraphQL query?

A GraphQL request over HTTP is JSON, and JSON has no type for binary data. Forced into Base64, a 1,200,000-byte file becomes 1,600,000 characters, a third bigger.

Meaning: Base64 is still fine for very small files, such as an icon of a few KB. Big files need another way.

⚡ A presigned URL: the file goes straight to storage

Write:

mutation {
  createCoverUpload(bookId: 4, contentType: "image/jpeg", size: 1200000) {
    uploadUrl
    key
    expiresAt
  }
}

Meaning: The server only hands out a one-time permission to upload. The client sends the file with PUT straight to uploadUrl, then attachCover joins the key to the book. The GraphQL server only serves two small mutations, however big the file is.

⚡ Size limits are kept on the server

Meaning: The client's numbers can lie. createCoverUpload refuses a size over 5 MB before a single byte is sent, then attachCover checks again the real size of the file that reached storage.

What you will learn