@remix-run/form-data-middleware
v0.1.1
Published
Middleware for parsing FormData from request bodies
Downloads
616
Readme
form-data-middleware
Middleware for parsing FormData from incoming request bodies for use with @remix-run/fetch-router.
Installation
npm install @remix-run/form-data-middlewareUsage
Use the formData() middleware at the router level to parse FormData from the request body and make it available on the request context as context.formData.
context.files will also be available as a map of File objects keyed by the name of the form field.
import { createRouter } from '@remix-run/fetch-router'
import { formData } from '@remix-run/form-data-middleware'
let router = createRouter({
middleware: [formData()],
})
router.post('/users', async (context) => {
let name = context.formData.get('name')
let email = context.formData.get('email')
// Handle file uploads
let avatar = context.files?.get('avatar')
return Response.json({ name, email, hasAvatar: !!avatar })
})Custom File Upload Handler
You can use a custom upload handler to customize how file uploads are handled. The return value of the upload handler will be used as the value of the form field in the FormData object.
import { formData } from '@remix-run/form-data-middleware'
import { writeFile } from 'node:fs/promises'
let router = createRouter({
middleware: [
formData({
async uploadHandler(upload) {
// Save to disk and return path
let path = `./uploads/${upload.name}`
await writeFile(path, Buffer.from(await upload.arrayBuffer()))
return path
},
}),
],
})Suppress Parse Errors
Some requests may contain invalid form data that cannot be parsed. You can suppress parse errors by setting suppressErrors to true. In these cases, context.formData will be an empty FormData object.
let router = createRouter({
middleware: [
formData({
suppressErrors: true, // Invalid form data won't throw
}),
],
})Related Packages
fetch-router- Router for the web Fetch APIform-data-parser- The underlying form data parser
License
See LICENSE
