### Basic Fastify Setup with @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/Readme.md Register the @fastify/formbody plugin with Fastify to enable parsing of URL-encoded form data. This example shows a basic POST route that echoes the parsed request body. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody')) fastify.post('/', (req, reply) => { reply.send(req.body) }) fastify.listen({ port: 8000 }, (err) => { if (err) throw err }) ``` -------------------------------- ### Install @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/Readme.md Install the @fastify/formbody plugin using npm. ```bash npm i @fastify/formbody ``` -------------------------------- ### Basic Form Parsing Example Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Demonstrates how to parse URL-encoded form data in a basic Fastify route. ```javascript fastify.post('/', async (request, reply) => { // request.body will contain the parsed form data return request.body }) ``` -------------------------------- ### HTML Form Integration Example Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Shows a basic HTML form that submits data to a Fastify backend using application/x-www-form-urlencoded. ```html





``` -------------------------------- ### Advanced Pattern: Request/Response Example Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md A complete flow showing a request with form data and a response, including setting appropriate headers. ```javascript fastify.post('/process', async (request, reply) => { const formData = request.body // Process form data... reply.header('X-Processed-By', 'FastifyFormbody') return { status: 'success', data: formData } }) ``` -------------------------------- ### Basic TypeScript Setup with @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Illustrates setting up @fastify/formbody in a TypeScript Fastify application, including defining request body types and configuring options like `bodyLimit`. ```typescript import fastify from 'fastify' import formbody from '@fastify/formbody' import type { FastifyFormbodyOptions } from '@fastify/formbody' interface FormData { name: string email: string message: string } const app = fastify() const options: FastifyFormbodyOptions = { bodyLimit: 1048576 } app.register(formbody, options) app.post<{ Body: FormData }>('/contact', (req, reply) => { const { name, email, message } = req.body reply.send({ received: true, contact: name }) }) app.listen({ port: 3000 }) ``` -------------------------------- ### Migration Guide: v4 to v8 Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Illustrates key changes and how to migrate from v4 to v8 of the fastify-formbody plugin, focusing on potential breaking changes or new features. ```javascript // Migration example might involve changes in option handling or default behaviors. // Specific code would depend on the exact differences between versions. // For instance, if default parser changed, update registration: // fastify.register(fastifyFormbody, { parser: require('querystring').parse }) console.log('Migration from v4 to v8 might require updating plugin options or parser configurations.') ``` -------------------------------- ### Default Parser Output Example Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/types.md Illustrates the output of the default fast-querystring parser for a standard URL-encoded form body. ```typescript // Input: "name=Alice&age=30" // Output: { name: 'Alice', age: '30' } ``` -------------------------------- ### TypeScript: Basic Form Data Handling Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Example of using fastify-formbody with TypeScript, demonstrating type-safe access to parsed form data. ```typescript import fastify from 'fastify' import fastifyFormbody from '@fastify/formbody' const app = fastify() interface MyFormData { name: string; age: number; } app.register(fastifyFormbody) app.post<{ Body: MyFormData }>('/submit', async (request, reply) => { const { name, age } = request.body console.log(`Name: ${name}, Age: ${age}`) return { received: true } }) ``` -------------------------------- ### Registering fastify-formbody with Options Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/types.md Example of registering the fastify-formbody plugin with custom options, including a specific body limit and a JSON parser. ```typescript import fastify from 'fastify' import formBodyPlugin, { FastifyFormbodyOptions } from '@fastify/formbody' const app = fastify() const options: FastifyFormbodyOptions = { bodyLimit: 2048576, parser: (str) => JSON.parse(str) // custom parser } app.register(formBodyPlugin, options) ``` -------------------------------- ### Project File Structure Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/MANIFEST.md Illustrates the directory layout of the Fastify Formbody project documentation. This helps users locate specific files like the README, API reference, and usage examples. ```text /workspace/home/output/ ├── MANIFEST.md ← This file (project manifest) ├── README.md ← Start here (navigation hub) ├── INDEX.md ← Detailed index and breakdown ├── overview.md ← Architecture and overview ├── api-reference.md ← Main function reference ├── types.md ← Type definitions ├── configuration.md ← Configuration guide ├── errors.md ← Error handling └── usage-examples.md ← Code examples ``` -------------------------------- ### Form Parsing with Body Limit Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Example showing form parsing with a specified body limit. If the body exceeds this limit, an error will be returned. ```javascript fastify.register(fastifyFormbody, { bodyLimit: 5000 // 5KB limit }) fastify.post('/', async (request, reply) => { return request.body }) ``` -------------------------------- ### Fastify Formbody v8 Nested Object Parsing with Custom Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md To achieve v4's nested object parsing behavior in v8, a custom parser using the 'qs' library must be provided. This example demonstrates the setup and expected output. ```javascript // To get v4 behavior, use custom parser: const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) // Input: foo[one]=a&foo[two]=b // Output: { foo: { one: 'a', two: 'b' } } ``` -------------------------------- ### Configure @fastify/formbody with Custom Parser (qs lib) Source: https://github.com/fastify/fastify-formbody/blob/main/Readme.md To enable nested object parsing, similar to older versions, install the 'qs' library and configure it as the parser for @fastify/formbody. This allows for parsing inputs like 'foo[one]=foo&foo[two]=bar' into nested objects. ```javascript const fastify = require('fastify')() const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: str => qs.parse(str) }) ``` -------------------------------- ### Advanced Pattern: Validation with Form Data Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Example of integrating schema validation with form data parsed by fastify-formbody. ```javascript fastify.register(fastifyFormbody) fastify.post('/validate', { schema: { body: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer', minimum: 18 } } } } }, async (request, reply) => { // request.body is already validated return request.body }) ``` -------------------------------- ### Integrate HTML Form with Fastify POST Handler Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md This example demonstrates a client-side HTML form that submits data via POST to a Fastify endpoint. The @fastify/formbody plugin on the server will automatically parse this `application/x-www-form-urlencoded` data. ```html
``` -------------------------------- ### Trigger Request Body Too Large Error Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md This example shows how to configure a small 'bodyLimit' and send a request that exceeds it, triggering a 413 Payload Too Large error. ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 10 // 10 bytes max }) fastify.post('/submit', (req, reply) => { reply.send(req.body) }) // Sending body: "field=verylongvalue" (exceeds 10 bytes) // Response: 413 status with JSON error // { "statusCode": 413, "code": "FST_ERR_CTP_BODY_TOO_LARGE", "error": "Payload Too Large", "message": "Request body is too large" } ``` -------------------------------- ### Configure @fastify/formbody with Custom Body Limit Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Register the plugin with a custom body limit to control the maximum bytes processed before an error is returned. This example sets the limit to 5MB. ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 5242880 // 5 MB }) ``` -------------------------------- ### Implement Custom Form Body Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Provide a custom function to parse URL-encoded form data. This example manually splits and decodes key-value pairs. ```javascript fastify.register(require('@fastify/formbody'), { parser: (str) => { const entries = str.split('&').map(pair => pair.split('=')) return Object.fromEntries( entries.map(([k, v]) => [ decodeURIComponent(k), decodeURIComponent(v || '') ]) ) } }) ``` -------------------------------- ### Configure Custom Body Size Limit Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md This snippet shows how to configure the @fastify/formbody plugin to accept larger form submissions by setting a custom `bodyLimit`. The example sets the limit to 10 MB. ```javascript const fastify = require('fastify')() // Allow larger forms (10 MB) fastify.register(require('@fastify/formbody'), { bodyLimit: 10485760 }) fastify.post('/upload-config', (req, reply) => { // Can now accept larger form submissions reply.send({ received: Object.keys(req.body).length }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Trigger Parser Registration Error Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Examples demonstrating how to trigger the 'parser must be a function' error by providing non-function values for the 'parser' option. ```javascript fastify.register(require('@fastify/formbody'), { parser: 'invalid' // Not a function }) // Error: parser must be a function fastify.register(require('@fastify/formbody'), { parser: {} // Not a function }) // Error: parser must be a function ``` -------------------------------- ### Fastify Formbody v4 Nested Object Parsing Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md In v4, Fastify Formbody used 'qs' by default, enabling nested object parsing. This example shows the input and output for a nested query string. ```javascript // v4 used qs by default fastify.register(require('@fastify/formbody')) // Input: foo[one]=a&foo[two]=b // Output: { foo: { one: 'a', two: 'b' } } ``` -------------------------------- ### Form Parsing with Custom Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Example of using a custom parser function to handle form data. This custom parser converts the string to a JSON object. ```javascript fastify.register(fastifyFormbody, { parser: (str) => { // Example: parse as JSON return JSON.parse(str) } }) fastify.post('/', async (request, reply) => { return request.body }) ``` -------------------------------- ### Fastify Formbody v8 Default Flat Parsing Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md In v8, Fastify Formbody defaults to 'fast-querystring', which results in flat parsing of nested query strings. This example illustrates the default input and output. ```javascript // v8 uses fast-querystring by default (flat) fastify.register(require('@fastify/formbody')) // Input: foo[one]=a&foo[two]=b // Output: { 'foo[one]': 'a', 'foo[two]': 'b' } ``` -------------------------------- ### Handle Custom Parser Function Errors Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md An example where a custom parser function throws an error due to invalid input format. Fastify typically returns a 500 error unless handled. ```javascript fastify.register(require('@fastify/formbody'), { parser: (str) => { if (!str.includes('=')) { throw new Error('Invalid form format') } return JSON.parse(str) // Could throw if not valid JSON } }) fastify.post('/form', (req, reply) => { // If parser throws, this handler never executes reply.send(req.body) }) ``` -------------------------------- ### Handle Plugin Registration Error with try-catch Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Demonstrates how to use a try-catch block to gracefully handle errors that occur during plugin registration, such as providing an invalid parser. ```javascript try { await fastify.register(require('@fastify/formbody'), { parser: someInvalidValue }) } catch (err) { console.error('Plugin registration failed:', err.message) } ``` -------------------------------- ### Handle Form with Array Values (Custom qs Parser) Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Demonstrates configuring @fastify/formbody to use the `qs` library for parsing, which correctly handles array values for repeated keys. ```javascript const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) fastify.post('/preferences', (req, reply) => { console.log(req.body) // { interest: ['sports', 'music', 'reading'], language: 'en' } reply.send(req.body) }) ``` -------------------------------- ### Import @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Import the fastifyFormbody module using require. ```javascript const fastifyFormbody = require('@fastify/formbody') ``` -------------------------------- ### Advanced Pattern: Scoped Registration Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Demonstrates how to register fastify-formbody with different configurations for specific routes using namespaces. ```javascript fastify.register(fastifyFormbody, { namespace: 'urlencoded', bodyLimit: 1000 }) fastify.register(fastifyFormbody, { namespace: 'jsonParser', parser: JSON.parse }) fastify.post('/urlencoded', async (request, reply) => { // Parsed using the 'urlencoded' namespace config return request.urlencodedBody }) fastify.post('/json', async (request, reply) => { // Parsed using the 'jsonParser' namespace config return request.jsonParserBody }) ``` -------------------------------- ### Default Parser Input/Output Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Demonstrates the default parser's behavior, which creates a flat object from form data. Bracket notation keys are treated literally. ```text Input: name=Alice&email=alice@example.com Output: { name: 'Alice', email: 'alice@example.com' } ``` ```text Input: user[name]=Alice&user[age]=30 Output: { 'user[name]': 'Alice', 'user[age]': '30' } ``` -------------------------------- ### Basic Usage of @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Register the plugin with default settings and handle POST requests with form-urlencoded data. The parsed body will be available in req.body. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody')) fastify.post('/contact', (req, reply) => { console.log(req.body) // { name: 'John', email: 'john@example.com' } reply.send({ success: true }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Set bodyLimit at Fastify Instance Level Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Demonstrates setting the 'bodyLimit' globally for the Fastify instance, which also affects the formbody plugin. ```javascript const fastify = require('fastify')({ bodyLimit: 52428800 }) fastify.register(require('@fastify/formbody')) ``` -------------------------------- ### TypeScript with Custom qs Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Shows how to use a custom `qs` parser within a TypeScript Fastify application to handle nested or complex form data structures. ```typescript import fastify from 'fastify' import formbody from '@fastify/formbody' import qs from 'qs' interface NestedForm { user: { name: string age: number } } const app = fastify() app.register(formbody, { parser: (str: string) => qs.parse(str) }) app.post<{ Body: NestedForm }>('/user', (req, reply) => { const userName = req.body.user.name reply.send({ registered: userName }) }) app.listen({ port: 3000 }) ``` -------------------------------- ### Configure @fastify/formbody with Options Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/README.md Register the plugin with custom options to set the body limit or provide a custom parser function. ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 5242880, // 5 MB parser: customParserFunc // Custom parser (optional) }) ``` -------------------------------- ### Multiple Routes with Different Parsers Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Register the formbody plugin globally for simple routes and use scoped plugins to apply custom parsers, like nested object parsing with 'qs', to specific route groups. ```javascript const fastify = require('fastify')() const qs = require('qs') // Register basic parser fastify.register(require('@fastify/formbody')) // For routes needing nested parsing, use a scoped plugin fastify.register(async (fastify) => { await fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) fastify.post('/nested', (req, reply) => { // This route has access to nested object parsing reply.send(req.body) }) }) fastify.post('/simple', (req, reply) => { // This route uses the default parser (flat structure) reply.send(req.body) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Plugin Registration with Options Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Register the fastify-formbody plugin with custom options, such as setting a body limit. ```javascript fastify.register(fastifyFormbody, { bodyLimit: 1024 * 1024 // 1MB }) ``` -------------------------------- ### Module Exports for @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Demonstrates the different ways the @fastify/formbody function can be exported and accessed, including default and named exports. ```javascript // All three refer to the same function: module.exports // default export module.exports.default // ES6 compatibility module.exports.fastifyFormbody // named export ``` -------------------------------- ### Handle Typical Form Submission Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Demonstrates how to process a standard URL-encoded form submission. The plugin automatically parses the request body into an object accessible via `req.body`. ```http POST /subscribe HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencoded Content-Length: 45 email=user@example.com&newsletter=on&frequency=weekly ``` ```javascript fastify.post('/subscribe', (req, reply) => { console.log(req.body) // { email: 'user@example.com', newsletter: 'on', frequency: 'weekly' } reply.send({ status: 'subscribed', email: req.body.email }) }) ``` ```json { "status": "subscribed", "email": "user@example.com" } ``` -------------------------------- ### Handle Form with Array Values (Default Parser) Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Shows how the default parser handles form submissions with multiple values for the same key. Note that the last value wins by default. ```http POST /preferences HTTP/1.1 Content-Type: application/x-www-form-urlencoded interest=sports&interest=music&interest=reading&language=en ``` ```javascript fastify.post('/preferences', (req, reply) => { console.log(req.body) // { interest: 'reading', language: 'en' } // Last value wins reply.send(req.body) }) ``` -------------------------------- ### Basic Plugin Registration Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Register the fastify-formbody plugin with Fastify. This is the simplest way to enable form data parsing. ```javascript import fastifyFormbody from '@fastify/formbody' fastify.register(fastifyFormbody) ``` -------------------------------- ### Handle Simple POST Request with Form Data Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md This snippet shows a basic Fastify POST handler that registers the @fastify/formbody plugin to parse incoming URL-encoded form data. The parsed data is available in `req.body`. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody')) fastify.post('/feedback', (req, reply) => { console.log('Form data received:', req.body) // req.body = { name: 'John', email: 'john@example.com', message: '...' } reply.send({ success: true, message: `Thank you ${req.body.name}` }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### TypeScript: Custom Parser with Type Safety Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Illustrates using a custom parser with TypeScript, ensuring type safety for the parsed form data. ```typescript import fastify from 'fastify' import fastifyFormbody, { FastifyFormbodyOptions } from '@fastify/formbody' const app = fastify() interface CustomParsedData { id: string; value: boolean; } const customParser = (str: string): CustomParsedData => { // Example: Parse a custom string format const [id, valueStr] = str.split(':') return { id, value: valueStr === 'true' } } const options: FastifyFormbodyOptions = { parser: customParser } app.register(fastifyFormbody, options) app.post<{ Body: CustomParsedData }>('/custom', async (request, reply) => { return request.body }) ``` -------------------------------- ### Register Plugin and Define Routes Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Register the @fastify/formbody plugin before defining routes that handle form-encoded data. This ensures proper parsing of request bodies. ```javascript const fastify = require('fastify')() // Register plugin first fastify.register(require('@fastify/formbody'), { bodyLimit: 1048576, parser: customParserFunction }) // Then define routes fastify.post('/form', (req, reply) => { // req.body contains parsed form data }) ``` -------------------------------- ### TypeScript Import for @fastify/formbody Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Import the fastifyFormbody module and its options type for TypeScript projects. ```typescript import fastifyFormbody from '@fastify/formbody' import type { FastifyFormbodyOptions } from '@fastify/formbody' ``` -------------------------------- ### Use qs Parser for Nested Objects Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Integrate the 'qs' library to parse nested objects within URL-encoded form data. This allows for more complex data structures. ```javascript const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) // Input body: "user[name]=John&user[age]=30" // Output: { user: { name: 'John', age: '30' } } ``` -------------------------------- ### Custom Parser for Nested Objects Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/types.md Shows how to use a custom parser, like qs.parse, to handle nested objects in the form body, such as array elements. ```typescript import qs from 'qs' app.register(formBodyPlugin, { parser: (str) => qs.parse(str) }) // Now arr[0]=val&arr[1]=val2 parses to { arr: ['val', 'val2'] } ``` -------------------------------- ### Fix Invalid Parser Registration Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Illustrates the correct way to register the formbody plugin by ensuring the 'parser' option is a valid function. ```javascript // Ensure parser is a function const customParser = (str) => { // parsing logic return {} } fastify.register(require('@fastify/formbody'), { parser: customParser // Must be a function }) ``` -------------------------------- ### Use Default Form Body Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Demonstrates the default parsing behavior for URL-encoded form data. The input string is parsed into a JavaScript object. ```javascript // Input body: "foo=bar&baz=qux" // Output: { foo: 'bar', baz: 'qux' } ``` -------------------------------- ### FastifyFormbodyOptions Interface Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/types.md Defines the configuration options for the fastify-formbody plugin, including body limit and a custom parser function. ```typescript interface FastifyFormbodyOptions { bodyLimit?: number parser?: (str: string) => Record } ``` -------------------------------- ### Increase bodyLimit to Fix Large Body Error Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Shows how to increase the 'bodyLimit' option when registering the formbody plugin to accommodate larger request bodies. ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 52428800 // 50 MB }) ``` -------------------------------- ### Handling Form Errors: Parser Must Be a Function Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Demonstrates how to catch the specific error that occurs if the provided parser is not a function during plugin registration. ```javascript fastify.register(fastifyFormbody, { parser: 'not a function' }).catch(err => { console.error(err.message) // 'parser must be a function' }) ``` -------------------------------- ### Configure @fastify/formbody with Custom Parsing Logic Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Register the plugin with a custom parser function that manually splits and decodes form-urlencoded strings. This provides fine-grained control over the parsing process. ```javascript fastify.register(require('@fastify/formbody'), { parser: (str) => { const pairs = str.split('&') const result = {} for (const pair of pairs) { const [key, value] = pair.split('=') result[decodeURIComponent(key)] = decodeURIComponent(value || '') } return result } }) ``` -------------------------------- ### Implement Custom Parser for Comma-Separated Values Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md This snippet demonstrates how to provide a custom `parser` function to @fastify/formbody. The custom logic parses comma-separated values into an array, handling specific data transformation needs. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody'), { parser: (str) => { // Custom parsing logic - convert comma-separated values const result = {} const pairs = str.split('&') for (const pair of pairs) { const [key, value] = pair.split('=') const decoded = { key: decodeURIComponent(key), value: decodeURIComponent(value || '') } // Split values by comma if they contain commas if (decoded.value.includes(',')) { result[decoded.key] = decoded.value.split(',') } else { result[decoded.key] = decoded.value } } return result } }) fastify.post('/tags', (req, reply) => { // Input: tags=javascript,node,fastify // req.body = { tags: ['javascript', 'node', 'fastify'] } reply.send({ tagCount: req.body.tags.length }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Plugin Registration with Custom Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Register the fastify-formbody plugin with a custom parser function to handle specific content types or data structures. ```javascript fastify.register(fastifyFormbody, { parser: (str) => { // Custom parsing logic here return JSON.parse(str) } }) ``` -------------------------------- ### Configure Formbody with Custom Parser Function Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Registers the @fastify/formbody plugin using a custom parser function, defined inline or imported, for processing form data. ```javascript const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) ``` -------------------------------- ### Register Formbody with Custom Parser Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Registers the @fastify/formbody plugin with a custom parser, such as 'qs', to enable nested object parsing. ```javascript fastify.register(require('@fastify/formbody'), { parser: require('qs').parse }) ``` -------------------------------- ### Register Formbody Plugin Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Registers the @fastify/formbody plugin with a Fastify instance. This enables parsing of URL-encoded form data. ```javascript fastify.register(require('@fastify/formbody'), options) ``` -------------------------------- ### Handling Form Errors: Body Too Large (413) Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/INDEX.md Shows how to handle the HTTP 413 error when the request body exceeds the configured body limit. ```javascript fastify.setErrorHandler((error, request, reply) => { if (error.code === 'FST_ফরমbody_TOO_LARGE') { reply.status(413).send({ message: 'Request body too large' }) } else { reply.send(error) } }) ``` -------------------------------- ### fastifyFormbody Plugin Registration Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md Registers the fastify-formbody plugin with a Fastify instance. It enables parsing of `application/x-www-form-urlencoded` request bodies. ```APIDOC ## fastifyFormbody Plugin ### Description Registers a content-type parser for `application/x-www-form-urlencoded` requests with the Fastify instance. The plugin processes incoming form data and populates `req.body` with the parsed form fields. ### Method ```javascript fastify.register(require('@fastify/formbody'), [options]) ``` ### Parameters #### Plugin Parameters - **fastify** (FastifyInstance) - Required - The Fastify instance to register the plugin with. - **options** (FastifyFormbodyOptions) - Optional - Configuration object for the plugin. - **done** ((error?: Error) => void) - Required - Callback function invoked after plugin registration. ### Options #### bodyLimit - **bodyLimit** (number) - Optional - Maximum bytes to process before returning an error. When undefined, uses the Fastify instance bodyLimit (default: 1048576). When exceeded, returns a 413 status code. #### parser - **parser** ((str: string) => Record) - Optional - Custom parser function for form-urlencoded strings. Receives the request body as a string and returns a parsed object. Defaults to `fast-querystring`. ### Error Handling - **Invalid Parser**: If the `parser` option is not a function, an error `'parser must be a function'` is thrown. - **Body Limit Exceeded**: Request bodies exceeding `bodyLimit` result in a 413 Payload Too Large HTTP response with the message `'Request body is too large'`. ### Example Usage **Basic Usage:** ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody')) fastify.post('/contact', (req, reply) => { console.log(req.body) reply.send({ success: true }) }) fastify.listen({ port: 3000 }) ``` **Custom Body Limit:** ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 5242880 // 5 MB }) ``` **Custom Parser (using qs):** ```javascript const qs = require('qs') fastify.register(require('@fastify/formbody'), { parser: (str) => qs.parse(str) }) ``` ``` -------------------------------- ### Handle 413 Payload Too Large Error in Client Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md Client-side code demonstrating how to catch a 413 response from the server and log the error message. ```javascript const response = await fetch('http://localhost:3000/submit', { method: 'POST', body: new URLSearchParams({ field: 'value' }) }) if (response.status === 413) { const error = await response.json() console.error('Form data too large:', error.message) } ``` -------------------------------- ### Fastify Formbody Function Signature Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/api-reference.md The function signature for registering the fastifyFormbody plugin with Fastify. ```javascript fastifyFormbody(fastify, options, done) ``` -------------------------------- ### Formbody with Custom Error Handling Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Implement a global error handler to catch and customize responses for specific formbody-related errors, such as exceeding the body size limit or invalid form data. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody'), { bodyLimit: 1048576 // 1 MB }) fastify.setErrorHandler((error, request, reply) => { if (error.code === 'FST_ERR_CTP_BODY_TOO_LARGE') { reply.status(413).send({ error: 'FORM_TOO_LARGE', message: 'Form data exceeds 1 MB limit', maxSize: 1048576 }) } else if (error.statusCode === 400) { reply.status(400).send({ error: 'INVALID_FORM', message: error.message }) } else { reply.status(500).send({ error: 'INTERNAL_ERROR', message: 'An unexpected error occurred' }) } }) fastify.post('/form', (req, reply) => { reply.send({ success: true, data: req.body }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Formbody with Validation Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/usage-examples.md Integrate formbody with Fastify's schema validation to automatically validate incoming form data against predefined rules before it reaches the route handler. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/formbody')) fastify.post('/registration', { schema: { body: { type: 'object', required: ['username', 'password', 'email'], properties: { username: { type: 'string', minLength: 3 }, password: { type: 'string', minLength: 8 }, email: { type: 'string', format: 'email' } } } } }, (req, reply) => { // Request body is validated by Fastify before this handler const { username, password, email } = req.body reply.send({ message: `User ${username} registered with email ${email}` }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Override Fastify Instance Body Limit Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Configure a specific body limit for form-encoded requests that differs from the global Fastify instance limit. This allows fine-grained control over request body sizes. ```javascript // Fastify instance with 1 MB limit const fastify = require('fastify')({ bodyLimit: 1048576 }) // Plugin with 5 MB limit for forms specifically fastify.register(require('@fastify/formbody'), { bodyLimit: 5242880 }) // Other content types still respect the 1 MB instance limit // Form-encoded requests use the 5 MB plugin limit ``` -------------------------------- ### Customize Parser Error Response with setErrorHandler Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md This code snippet shows how to use Fastify's 'setErrorHandler' to catch specific errors thrown by the custom parser and return a more appropriate client-friendly error response (e.g., 400 Bad Request). ```javascript fastify.setErrorHandler((error, request, reply) => { if (error.message.includes('Invalid form format')) { reply.status(400).send({ error: 'Bad form data' }) } else { reply.status(500).send({ error: 'Internal server error' }) } }) ``` -------------------------------- ### Set Body Limit for Form Data Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Configure the maximum size for URL-encoded request bodies. This overrides the Fastify instance's default body limit for form data specifically. The limit is in bytes. ```javascript fastify.register(require('@fastify/formbody'), { bodyLimit: 2097152 // 2 MB }) ``` -------------------------------- ### Handle Large Form Errors Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/overview.md Sets up a custom error handler for the Fastify instance to specifically catch and respond to 'Form too large' errors (HTTP status code 413). ```javascript fastify.setErrorHandler((error, request, reply) => { if (error.statusCode === 413) { reply.status(413).send({ error: 'Form too large' }) } }) ``` -------------------------------- ### Access Parsed Form Data in Route Handler Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/configuration.md Access the parsed form data directly from `req.body` within your route handler. The plugin handles parsing before the handler executes. ```javascript fastify.post('/endpoint', (req, reply) => { req.body // parsed form data as an object }) ``` -------------------------------- ### Validate Parser Function Type Source: https://github.com/fastify/fastify-formbody/blob/main/_autodocs/errors.md This code checks if the provided 'parser' option is a function during plugin registration. It throws an error if the type is incorrect. ```javascript if (typeof opts.parser !== 'function') { next(new Error('parser must be a function')) return } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.