### 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