{"id":13836118,"url":"https://github.com/fastify/fastify-multipart","last_synced_at":"2025-05-13T20:15:00.645Z","repository":{"id":37602457,"uuid":"87714580","full_name":"fastify/fastify-multipart","owner":"fastify","description":"Multipart support for Fastify","archived":false,"fork":false,"pushed_at":"2025-05-01T09:34:29.000Z","size":478,"stargazers_count":505,"open_issues_count":16,"forks_count":106,"subscribers_count":16,"default_branch":"main","last_synced_at":"2025-05-05T12:43:22.651Z","etag":null,"topics":["fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/multipart","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2017-04-09T14:31:08.000Z","updated_at":"2025-05-01T09:34:26.000Z","dependencies_parsed_at":"2024-04-12T11:01:56.497Z","dependency_job_id":"e0eaef16-a10a-4a11-98b5-3d238872a9b2","html_url":"https://github.com/fastify/fastify-multipart","commit_stats":{"total_commits":371,"total_committers":86,"mean_commits":4.313953488372093,"dds":0.7816711590296496,"last_synced_commit":"ff9530b91d8f124640a6b6e2c2fee67f7b0fbac6"},"previous_names":[],"tags_count":72,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-multipart","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-multipart/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-multipart/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-multipart/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-multipart/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252978691,"owners_count":21834914,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","fastify-plugin"],"created_at":"2024-08-04T15:00:35.926Z","updated_at":"2025-05-13T20:15:00.621Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/multipart\n\n[![CI](https://github.com/fastify/fastify-multipart/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-multipart/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/multipart.svg?style=flat)](https://www.npmjs.com/package/@fastify/multipart)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nFastify plugin to parse the multipart content-type. Supports:\n\n- Async / Await\n- Async iterator support to handle multiple parts\n- Stream \u0026 Disk mode\n- Accumulating the entire file in memory\n- Mode to attach all fields to the request body\n- Tested across Linux/Mac/Windows\n\nUnder the hood, it uses [`@fastify/busboy`](https://github.com/fastify/busboy).\n\n## Install\n```sh\nnpm i @fastify/multipart\n```\n\n## Usage\n\n```js\nconst fastify = require('fastify')()\nconst fs = require('node:fs')\nconst { pipeline } = require('node:stream/promises')\n\nfastify.register(require('@fastify/multipart'))\n\nfastify.post('/', async function (req, reply) {\n  // process a single file\n  // also, consider that if you allow to upload multiple files\n  // you must consume all files otherwise the promise will never fulfill\n  const data = await req.file()\n\n  data.file // stream\n  data.fields // other parsed parts\n  data.fieldname\n  data.filename\n  data.encoding\n  data.mimetype\n\n  // to accumulate the file in memory! Be careful!\n  //\n  // await data.toBuffer() // Buffer\n  //\n  // or\n\n  await pipeline(data.file, fs.createWriteStream(data.filename))\n\n  // be careful of permission issues on disk and not overwrite\n  // sensitive files that could cause security risks\n\n  // also, consider that if the file stream is not consumed, the promise will never fulfill\n\n  reply.send()\n})\n\nfastify.listen({ port: 3000 }, err =\u003e {\n  if (err) throw err\n  console.log(`server listening on ${fastify.server.address().port}`)\n})\n```\n\n**Note** about `data.fields`: `busboy` consumes the multipart in serial order (stream). Therefore, the order of form fields is *VERY IMPORTANT* to how `@fastify/multipart` can display the fields to you.\nWe would recommend you place the value fields first before any of the file fields.\nIt will ensure your fields are accessible before it starts consuming any files.\nIf you cannot control the order of the placed fields, be sure to read `data.fields` *AFTER* consuming the stream, or it will only contain the fields parsed at that moment.\n\nYou can also pass optional arguments to `@fastify/busboy` when registering with Fastify. This is useful for setting limits on the content that can be uploaded. A full list of available options can be found in the [`@fastify/busboy` documentation](https://github.com/fastify/busboy#busboy-methods).\n\n```js\nfastify.register(require('@fastify/multipart'), {\n  limits: {\n    fieldNameSize: 100, // Max field name size in bytes\n    fieldSize: 100,     // Max field value size in bytes\n    fields: 10,         // Max number of non-file fields\n    fileSize: 1000000,  // For multipart forms, the max file size in bytes\n    files: 1,           // Max number of file fields\n    headerPairs: 2000,  // Max number of header key=\u003evalue pairs\n    parts: 1000         // For multipart forms, the max number of parts (fields + files)\n  }\n});\n```\n\nFor security reasons, `@fastify/multipart` sets the limit for `parts` and `fileSize` being _1000_ and _1048576_ respectively.\n\n**Note**: if the file stream that is provided by `data.file` is not consumed, like in the example below with the usage of pipeline, the promise will not be fulfilled at the end of the multipart processing.\nThis behavior is inherited from [`@fastify/busboy`](https://github.com/fastify/busboy).\n\n**Note**: if you set a `fileSize` limit and you want to know if the file limit was reached you can:\n- listen to `data.file.on('limit')`\n- or check at the end of the stream the property `data.file.truncated`\n- or call `data.file.toBuffer()` and wait for the error to be thrown\n\n```js\nconst data = await req.file()\nawait pipeline(data.file, fs.createWriteStream(data.filename))\nif (data.file.truncated) {\n  // you may need to delete the part of the file that has been saved on disk\n  // before the `limits.fileSize` has been reached\n  reply.send(new fastify.multipartErrors.FilesLimitError());\n}\n\n// OR\nconst data = await req.file()\ntry {\n  const buffer = await data.toBuffer()\n} catch (err) {\n  // fileSize limit reached!\n}\n\n```\n\nAdditionally, you can pass per-request options to the  `req.file`, `req.files`, `req.saveRequestFiles` or `req.parts` function.\n\n```js\nfastify.post('/', async function (req, reply) {\n  const options = { limits: { fileSize: 1000 } };\n  const data = await req.file(options)\n  await pipeline(data.file, fs.createWriteStream(data.filename))\n  reply.send()\n})\n```\n\n## Handle multiple file streams\n\n```js\nfastify.post('/', async function (req, reply) {\n  const parts = req.files()\n  for await (const part of parts) {\n    await pipeline(part.file, fs.createWriteStream(part.filename))\n  }\n  reply.send()\n})\n```\n\n## Handle multiple file streams and fields\n\n```js\nfastify.post('/upload/raw/any', async function (req, reply) {\n  const parts = req.parts()\n  for await (const part of parts) {\n    if (part.type === 'file') {\n      await pipeline(part.file, fs.createWriteStream(part.filename))\n    } else {\n      // part.type === 'field\n      console.log(part)\n    }\n  }\n  reply.send()\n})\n```\n\n## Accumulating the entire file in memory\n\n```js\nfastify.post('/upload/raw/any', async function (req, reply) {\n  const data = await req.file()\n  const buffer = await data.toBuffer()\n  // upload to S3\n  reply.send()\n})\n```\n\n\n## Upload files to disk and work with temporary file paths\n\nThis will store all files in the operating system's default directory for temporary files. As soon as the response ends all files are removed.\n\n```js\nfastify.post('/upload/files', async function (req, reply) {\n  // stores files to tmp dir and return files\n  const files = await req.saveRequestFiles()\n  files[0].type // \"file\"\n  files[0].filepath\n  files[0].fieldname\n  files[0].filename\n  files[0].encoding\n  files[0].mimetype\n  files[0].fields // other parsed parts\n\n  reply.send()\n})\n```\n\n## Handle file size limitation\n\nIf you set a `fileSize` limit, it can throw a `RequestFileTooLargeError` error when limit reached.\n\n```js\nfastify.post('/upload/files', async function (req, reply) {\n  try {\n    const file = await req.file({ limits: { fileSize: 17000 } })\n    //const files = req.files({ limits: { fileSize: 17000 } })\n    //const parts = req.parts({ limits: { fileSize: 17000 } })\n    //const files = await req.saveRequestFiles({ limits: { fileSize: 17000 } })\n    reply.send()\n  } catch (error) {\n    // error instanceof fastify.multipartErrors.RequestFileTooLargeError\n  }\n})\n```\n\nIf you want to fallback to the handling before `4.0.0`, you can disable the throwing behavior by passing `throwFileSizeLimit`.\nNote: It will not affect the behavior of `saveRequestFiles()`\n\n```js\n// globally disable\nfastify.register(fastifyMultipart, { throwFileSizeLimit: false })\n\nfastify.post('/upload/file', async function (req, reply) {\n  const file = await req.file({ throwFileSizeLimit: false, limits: { fileSize: 17000 } })\n  //const files = req.files({ throwFileSizeLimit: false, limits: { fileSize: 17000 } })\n  //const parts = req.parts({ throwFileSizeLimit: false, limits: { fileSize: 17000 } })\n  //const files = await req.saveRequestFiles({ throwFileSizeLimit: false, limits: { fileSize: 17000 } })\n  reply.send()\n})\n```\n\n## Parse all fields and assign them to the body\n\nThis allows you to parse all fields automatically and assign them to the `request.body`. By default, files are accumulated in memory (Be careful!) to buffer objects. Uncaught errors are [handled](https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md#manage-errors-from-a-hook) by Fastify.\n\n```js\nfastify.register(require('@fastify/multipart'), { attachFieldsToBody: true })\n\nfastify.post('/upload/files', async function (req, reply) {\n  const uploadValue = await req.body.upload.toBuffer() // access files\n  const fooValue = req.body.foo.value                  // other fields\n  const body = Object.fromEntries(\n    Object.keys(req.body).map((key) =\u003e [key, req.body[key].value])\n  ) // Request body in key-value pairs, like req.body in Express (Node 12+)\n\n  // On Node 18+\n  const formData = await req.formData()\n  console.log(formData)\n})\n```\n\nRequest body key-value pairs can be assigned directly using `attachFieldsToBody: 'keyValues'`. Field values, including file buffers, will be attached to the body object.\n\n```js\nfastify.register(require('@fastify/multipart'), { attachFieldsToBody: 'keyValues' })\n\nfastify.post('/upload/files', async function (req, reply) {\n  const uploadValue = req.body.upload // access file as buffer\n  const fooValue = req.body.foo       // other fields\n})\n```\n\nYou can also define an `onFile` handler to avoid accumulating all files in memory.\n\n```js\nasync function onFile(part) {\n  // you have access to original request via `this`\n  console.log(this.id)\n  await pipeline(part.file, fs.createWriteStream(part.filename))\n}\n\nfastify.register(require('@fastify/multipart'), { attachFieldsToBody: true, onFile })\n\nfastify.post('/upload/files', async function (req, reply) {\n  const fooValue = req.body.foo.value // other fields\n})\n```\n\nThe `onFile` handler can also be used with `attachFieldsToBody: 'keyValues'` in order to specify how file buffer values are decoded.\n\n```js\nasync function onFile(part) {\n  const buff = await part.toBuffer()\n  const decoded = Buffer.from(buff.toString(), 'base64').toString()\n  part.value = decoded // set `part.value` to specify the request body value\n}\n\nfastify.register(require('@fastify/multipart'), { attachFieldsToBody: 'keyValues', onFile })\n\nfastify.post('/upload/files', async function (req, reply) {\n  const uploadValue = req.body.upload // access file as base64 string\n  const fooValue = req.body.foo       // other fields\n})\n```\n\n**Note**: if you assign all fields to the body and don't define an `onFile` handler, you won't be able to read the files through streams, as they are already read and their contents are accumulated in memory.\nYou can only use the `toBuffer` method to read the content.\nIf you try to read from a stream and pipe to a new file, you will obtain an empty new file.\n\n## JSON Schema body validation\n\nWhen the `attachFieldsToBody` parameter is set to `'keyValues'`, JSON Schema validation on the body will behave similarly to `application/json` and [`application/x-www-form-urlencoded`](https://github.com/fastify/fastify-formbody) content types. Additionally, uploaded files will be attached to the body as `Buffer` objects.\n\n```js\nfastify.register(require('@fastify/multipart'), { attachFieldsToBody: 'keyValues' })\n\nfastify.post('/upload/files', {\n  schema: {\n    consumes: ['multipart/form-data'],\n    body: {\n      type: 'object',\n      required: ['myFile'],\n      properties: {\n        // file that gets decoded to string\n        myFile: {\n          type: 'object',\n        },\n        hello: {\n          type: 'string',\n          enum: ['world']\n        }\n      }\n    }\n  }\n}, function (req, reply) {\n  console.log({ body: req.body })\n  reply.send('done')\n})\n```\n\nIf you enable `attachFieldsToBody: true` and set `sharedSchemaId` a shared JSON Schema is added, which can be used to validate parsed multipart fields.\n\n```js\nconst opts = {\n  attachFieldsToBody: true,\n  sharedSchemaId: '#mySharedSchema'\n}\nfastify.register(require('@fastify/multipart'), opts)\n\nfastify.post('/upload/files', {\n  schema: {\n    consumes: ['multipart/form-data'],\n    body: {\n      type: 'object',\n      required: ['myField'],\n      properties: {\n        // field that uses the shared schema\n        myField: { $ref: '#mySharedSchema'},\n        // or another field that uses the shared schema\n        myFiles: { type: 'array', items: fastify.getSchema('mySharedSchema') },\n        // or a field that doesn't use the shared schema\n        hello: {\n          properties: {\n            value: {\n              type: 'string',\n              enum: ['male']\n            }\n          }\n        }\n      }\n    }\n  }\n}, function (req, reply) {\n  console.log({ body: req.body })\n  reply.send('done')\n})\n```\n\nIf provided, the `sharedSchemaId` parameter must be a string ID and a shared schema will be added to your fastify instance so you will be able to apply the validation to your service (like in the example mentioned above).\n\nThe shared schema, that is added, will look like this:\n```js\n{\n  type: 'object',\n  properties: {\n    encoding: { type: 'string' },\n    filename: { type: 'string' },\n    limit: { type: 'boolean' },\n    mimetype: { type: 'string' }\n  }\n}\n```\n\n### JSON Schema with Swagger\n\nIf you want to use `@fastify/multipart` with `@fastify/swagger` and `@fastify/swagger-ui` you must add a new type called `isFile` and use a custom instance of a validator compiler [Docs](https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#validator-compiler).\n\n```js\n\nconst fastify = require('fastify')({\n // ...\n  ajv: {\n    // Adds the file plugin to help @fastify/swagger schema generation\n    plugins: [require('@fastify/multipart').ajvFilePlugin]\n  }\n})\n\nfastify.register(require(\"@fastify/multipart\"), {\n  attachFieldsToBody: true,\n});\n\nfastify.post(\n  \"/upload/files\",\n  {\n    schema: {\n      consumes: [\"multipart/form-data\"],\n      body: {\n        type: \"object\",\n        required: [\"myField\"],\n        properties: {\n          myField: { isFile: true },\n        },\n      },\n    },\n  },\n  function (req, reply) {\n    console.log({ body: req.body });\n    reply.send(\"done\");\n  }\n);\n\n```\n\n\n### JSON Schema non-file field\nWhen sending fields with the body (`attachFieldsToBody` set to true), the field might look like this in the `request.body`:\n```json\n{\n  \"hello\": \"world\"\n}\n```\nThe mentioned field will be converted, by this plugin, to a more complex field. The converted field will look something like this:\n```js\n{\n  hello: {\n    fieldname: \"hello\",\n    value: \"world\",\n    fieldnameTruncated: false,\n    valueTruncated: false,\n    fields: body\n  }\n}\n```\n\nIt is important to know that this conversion happens BEFORE the field is validated, so keep that in mind when writing the JSON schema for validation for fields that don't use the shared schema. The schema for validation for the field mentioned above should look like this:\n```js\nhello: {\n  properties: {\n    value: {\n      type: 'string'\n    }\n  }\n}\n```\n\n#### JSON non-file fields\n\nIf a non-file field sent has `Content-Type` header starting with `application/json`, it will be parsed using `JSON.parse`.\n\nThe schema to validate JSON fields should look like this:\n\n```js\nhello: {\n  properties: {\n    value: {\n      type: 'object',\n      properties: {\n        /* ... */\n      }\n    }\n  }\n}\n```\n\nIf you also use the shared JSON schema as shown above, this is a full example that validates the entire field:\n\n```js\nconst opts = {\n  attachFieldsToBody: true,\n  sharedSchemaId: '#mySharedSchema'\n}\nfastify.register(require('@fastify/multipart'), opts)\n\nfastify.post('/upload/files', {\n  schema: {\n    consumes: ['multipart/form-data'],\n    body: {\n      type: 'object',\n      required: ['field'],\n      properties: {\n        field: {\n          allOf: [\n            { $ref: '#mySharedSchema' },\n            {\n              properties: {\n                value: {\n                  type: 'object'\n                  properties: {\n                    child: {\n                      type: 'string'\n                    }\n                  }\n                }\n              }\n            }\n          ]\n        }\n      }\n    }\n  }\n}, function (req, reply) {\n  console.log({ body: req.body })\n  reply.send('done')\n})\n```\n\n## Access all errors\n\nWe export all custom errors via a server decorator `fastify.multipartErrors`. This is useful if you want to react to specific errors. They are derived from [@fastify/error](https://github.com/fastify/fastify-error) and include the correct `statusCode` property.\n\n```js\nfastify.post('/upload/files', async function (req, reply) {\n  const { FilesLimitError } = fastify.multipartErrors\n})\n```\n\n## Acknowledgments\n\nThis project is kindly sponsored by:\n- [nearForm](https://nearform.com)\n- [LetzDoIt](https://www.letzdoitapp.com/)\n- [platformatic](https://platformatic.dev)\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["\u003ch2 align=\"center\"\u003eAwesome Fastify\u003c/h2\u003e","JavaScript"],"sub_categories":["\u003ch2 align=\"center\"\u003eEcosystem\u003c/h2\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-multipart","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-multipart","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-multipart/lists"}