### AWS Lambda Fastify Example Configuration File Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md An example configuration file for AWS Lambda Fastify, showcasing various options for binary response handling, request/response processing, query and path handling, and Lambda behavior. ```javascript // config/lambda-options.js module.exports = { // Binary response handling binaryMimeTypes: [ 'application/octet-stream', 'application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'video/mp4', 'application/zip' ], // Request handling decorateRequest: true, decorationPropertyName: 'awsLambda', serializeLambdaArguments: process.env.SERIALIZE_LAMBDA === 'true', // Query parameter handling parseCommaSeparatedQueryParams: true, // Path handling retainStage: process.env.RETAIN_STAGE === 'true', pathParameterUsedAsPath: process.env.PROXY_PARAM || false, // Response handling payloadAsStream: process.env.USE_STREAMING === 'true', albMultiValueHeaders: process.env.ALB_MODE === 'true', // Lambda behavior callbackWaitsForEmptyEventLoop: false } ``` -------------------------------- ### Install @fastify/aws-lambda Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md Install the package using npm. This is the first step to integrate Fastify with AWS Lambda. ```bash $ npm i @fastify/aws-lambda ``` -------------------------------- ### awsLambdaFastify Usage Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/types.md Demonstrates how to instantiate `awsLambdaFastify` with various configuration options. This example shows common settings for binary MIME types, argument serialization, request decoration, stage retention, query parameter parsing, and payload streaming. ```javascript const proxy = awsLambdaFastify(app, { binaryMimeTypes: ['application/octet-stream', 'image/png', 'image/jpeg'], serializeLambdaArguments: false, decorateRequest: true, decorationPropertyName: 'awsLambda', retainStage: false, parseCommaSeparatedQueryParams: true, payloadAsStream: false }) ``` -------------------------------- ### PromiseHandler Usage Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/types.md Shows how to use the `PromiseHandler` type with `awsLambdaFastify`. The example demonstrates explicitly typing the handler's result. ```javascript const handler = awsLambdaFastify(app) // Explicitly typed: const result = await handler(event, context) // result is Promise ``` -------------------------------- ### Basic Handler Configuration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Initial setup for awsLambdaFastify with common options like binaryMimeTypes, serializeLambdaArguments, and decorateRequest. ```javascript const handler = awsLambdaFastify(app, { binaryMimeTypes: ['application/octet-stream'], serializeLambdaArguments: false, decorateRequest: true, // ... more options }) ``` -------------------------------- ### ALB Event Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Illustrates the raw ALB event structure and its transformed version for Fastify. ```javascript { version: '2.0', requestContext: { http: { method: 'GET', path: '/health', sourceIp: '10.0.0.1' }, elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' } }, rawPath: '/health', rawQueryString: '', headers: { 'host': 'internal-alb.example.com' }, multiValueHeaders: { 'x-forwarded-for': ['192.0.2.1'] }, multiValueQueryStringParameters: null, body: null, isBase64Encoded: false } ``` ```javascript { method: 'GET', url: '/health', query: {}, headers: { 'host': 'internal-alb.example.com', 'x-forwarded-for': ['192.0.2.1'] }, payload: null, remoteAddress: '192.0.2.1' // extracted from source IP } ``` -------------------------------- ### AWS Lambda Fastify Usage Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/types.md Example of how to use the awsLambdaFastify function. The comment shows the expected structure of the response object returned by the function. ```javascript const response = await awsLambdaFastify(app)(event, context) // response structure: // { // statusCode: 200, // headers: { 'content-type': 'application/json' }, // body: '{"hello":"world"}', // isBase64Encoded: false, // cookies: undefined // } ``` -------------------------------- ### Header Example: Simple Header Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Shows how a simple custom header is passed through. The `event.headers` object contains the custom headers. ```text event.headers: { 'x-custom': 'value' } Result headers: { 'x-custom': 'value' } ``` -------------------------------- ### Basic Lambda Handler Setup Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md Sets up the AWS Lambda handler by proxying a Fastify application. Shows default and configurable options for binary types and argument serialization. ```javascript const awsLambdaFastify = require('@fastify/aws-lambda') const app = require('./app') const proxy = awsLambdaFastify(app) // or // const proxy = awsLambdaFastify(app, { binaryMimeTypes: ['application/octet-stream'], serializeLambdaArguments: false /* default is true */ }) exports.handler = proxy // or // exports.handler = (event, context, callback) => proxy(event, context, callback) // or // exports.handler = (event, context) => proxy(event, context) // or // exports.handler = async (event, context) => proxy(event, context) ``` -------------------------------- ### Header Example: Multi-Value Header (1 value) Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Demonstrates how a single value in `event.multiValueHeaders` is handled when `albMultiValueHeaders` is false. Fastify simplifies it to a string value. ```text event.multiValueHeaders: { 'x-single': ['val1'] } Result headers: { 'x-single': 'val1' } // Only with albMultiValueHeaders: false ``` -------------------------------- ### API Gateway v2.0 Event Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Shows the raw structure of an API Gateway v2.0 event and its processed representation for Fastify. ```javascript { version: '2.0', routeKey: 'GET /users/{id}', rawPath: '/users/123', rawQueryString: 'filter=active&tags=a,b', headers: { 'host': 'api.example.com', 'x-custom': 'value' }, queryStringParameters: { 'filter': 'active', 'tags': 'a,b' }, pathParameters: { 'id': '123' }, requestContext: { http: { method: 'GET', path: '/users/123', sourceIp: '203.0.113.1' }, requestId: 'c6af9ac6...', stage: 'prod' }, body: null, isBase64Encoded: false, cookies: ['sessionId=abc123'] } ``` ```javascript { method: 'GET', url: '/users/123', query: { filter: 'active', tags: ['a', 'b'] // parsed from comma-separated }, headers: { 'host': 'api.example.com', 'x-custom': 'value', 'cookie': 'sessionId=abc123', // merged from cookies array 'x-request-id': 'c6af9ac6...' // extracted from requestContext.requestId }, payload: null, remoteAddress: '203.0.113.1' } ``` -------------------------------- ### Lower Cold Start Latency with Top-Level Await Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md Utilizes top-level await for faster cold starts in Node.js ES modules on AWS Lambda. The `fastify.ready()` call must be placed after `awsLambdaFastify`. ```javascript import awsLambdaFastify from '@fastify/aws-lambda' import app from './app.js' export const handler = awsLambdaFastify(app) await app.ready() // needs to be placed after awsLambdaFastify call because of the decoration: https://github.com/fastify/aws-lambda-fastify/blob/main/index.js#L9 ``` -------------------------------- ### Header Example: Multi-Value Header (2 values) Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Illustrates how multiple values for the same header are handled when provided in `event.multiValueHeaders`. Fastify preserves them as an array. ```text event.multiValueHeaders: { 'x-multi': ['val1', 'val2'] } Result headers: { 'x-multi': ['val1', 'val2'] } ``` -------------------------------- ### ALB Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Example of returning multi-value Set-Cookie headers for ALB. ```json { statusCode: 200, multiValueHeaders: { 'set-cookie': ['cookie1=value1', 'cookie2=value2'] }, isBase64Encoded: false } ``` -------------------------------- ### Proxy Integration Configuration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Configure for proxy integration, where path parameters are used as the path. This preset ensures correct routing for proxy-like setups. ```javascript awsLambdaFastify(app, { pathParameterUsedAsPath: 'proxy', retainStage: false, parseCommaSeparatedQueryParams: true }) ``` -------------------------------- ### TypeScript Export and Usage Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/module-graph.md Illustrates the TypeScript definition for aws-lambda-fastify and provides an example of its usage in a TypeScript project. ```APIDOC ## TypeScript Export ### Type Definition ```typescript // types/index.d.ts declare function awsLambdaFastify( app: FastifyInstance, options?: TOptions ): PromiseHandler | CallbackHandler export = awsLambdaFastify ``` ### Usage ```typescript import awsLambdaFastify from '@fastify/aws-lambda' const handler = awsLambdaFastify(app) ``` ``` -------------------------------- ### Complete Mixed Content API Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md This snippet demonstrates a full Fastify application configured for AWS Lambda, including enabling compression and defining routes for JSON, binary images, and binary PDFs. It shows how to set up `awsLambdaFastify` with `binaryMimeTypes` to ensure correct encoding of binary responses. ```javascript const fastify = require('fastify') const compress = require('@fastify/compress') const awsLambdaFastify = require('@fastify/aws-lambda') const app = fastify() // Enable compression app.register(compress, { global: true, encodings: ['br', 'gzip'] }) app.get('/api/data', (request, reply) => { reply.header('Content-Type', 'application/json') reply.send({ data: 'json' }) // If compressed: auto base64-encoded // If not: sent as-is }) app.get('/image/:id', (request, reply) => { reply.header('Content-Type', 'image/png') reply.send(pngBuffer) // Matches binaryMimeTypes → base64-encoded }) app.post('/export', (request, reply) => { reply.header('Content-Type', 'application/pdf') reply.header('Content-Disposition', 'attachment; filename=report.pdf') reply.send(pdfBuffer) // Matches binaryMimeTypes → base64-encoded }) const proxy = awsLambdaFastify(app, { binaryMimeTypes: [ 'image/png', 'image/jpeg', 'application/pdf', 'application/zip' ], // Compression already detected by default behavior }) exports.handler = proxy ``` -------------------------------- ### Custom Binary Response Handling with enforceBase64 Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md This example shows how to add custom rules for binary response detection using the `enforceBase64` option. When `enforceBase64` is provided, it replaces the built-in Content-Encoding default, so any desired compression checks must be reimplemented within the custom function. ```javascript exports.handler = awsLambdaFastify(app, { binaryMimeTypes: ['application/octet-stream', 'image/png'], // Custom rule for binary detection. Note: when you pass enforceBase64, // it REPLACES the built-in Content-Encoding default — it doesn't compose. // Re-implement the compression check yourself if you still want it. enforceBase64: (res) => { if (res.headers['content-type'] === 'application/x-protobuf') return true const enc = res.headers['content-encoding'] return !!enc && enc !== 'identity' } }) ``` -------------------------------- ### Callback-Based Lambda Handler Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/types.md Illustrates how to use the awsLambdaFastify wrapper with a callback-based handler. Ensure the inner handler correctly calls the provided callback. ```javascript const handler = awsLambdaFastify(app) // Callback-based invocation: exports.handler = (event, context, callback) => { handler(event, context, (err, result) => { if (err) return callback(err) callback(null, result) }) } ``` -------------------------------- ### Query Parameter Example: Single Value Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Demonstrates how a single query parameter is parsed. The `query` parameter allows Fastify to handle query string merging and parsing. ```text Event: ?foo=bar Result: { foo: 'bar' } ``` -------------------------------- ### Basic Fastify App Deployment to AWS Lambda Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/api-reference/awslambdafastify.md Use this for a standard Fastify application deployed to AWS Lambda using the promise pattern. Ensure you have fastify and @fastify/aws-lambda installed. ```javascript const fastify = require('fastify') const awsLambdaFastify = require('@fastify/aws-lambda') const app = fastify() app.get('/', (request, reply) => { reply.send({ hello: 'world' }) }) exports.handler = awsLambdaFastify(app) ``` -------------------------------- ### AWS Lambda Fastify Handler Usage Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Example of how to use the awsLambdaFastify function to create a Lambda handler, passing in the Fastify application instance and configuration options. ```javascript const awsLambdaFastify = require('@fastify/aws-lambda') const app = require('./app') const options = require('./config/lambda-options') exports.handler = awsLambdaFastify(app, options) ``` -------------------------------- ### API Gateway v2.0 Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Example of returning multi-value cookies for API Gateway v2.0. ```json { statusCode: 200, headers: { ... }, cookies: ['cookie1=value1', 'cookie2=value2'], isBase64Encoded: false } ``` -------------------------------- ### Query Parameter Example: URL-Encoded Values Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Demonstrates Fastify's automatic URL decoding for query parameter values. Values like 'foo%40bar' are automatically converted to 'foo@bar'. ```text Event.queryStringParameters: { foo: 'foo%40bar' } Result: { foo: 'foo@bar' } // Auto-decoded by Fastify ``` -------------------------------- ### Empty Body Event Handling Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Handles requests with no body, such as GET requests. The Fastify request body will be null. ```javascript event: { httpMethod: 'GET', body: null } Result: Fastify request.body = null ``` -------------------------------- ### API Gateway v1.0 Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Example of returning multi-value Set-Cookie headers for API Gateway v1.0. ```json { statusCode: 200, headers: { ... }, multiValueHeaders: { 'set-cookie': ['cookie1=value1', 'cookie2=value2'] }, isBase64Encoded: false } ``` -------------------------------- ### Query Parameter Example: Multi-Value (API Gateway v1.0) Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Illustrates multi-value query parameter handling for API Gateway v1.0. Fastify correctly parses parameters listed in both `queryStringParameters` and `multiValueQueryStringParameters`. ```text Event.queryStringParameters: { foo: 'bar' } Event.multiValueQueryStringParameters: { foo: ['qux', 'bar'] } Result: { foo: ['qux', 'bar'] } ``` -------------------------------- ### Response with No Encoding Field Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example where the 'isBase64Encoded' field is absent, which implies no encoding when disableBase64Encoding is true. ```javascript { statusCode: 200, headers: { 'content-type': 'application/json' }, body: '{"data":"value"}' // Note: isBase64Encoded field is absent } ``` -------------------------------- ### ALB Response with Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of an Application Load Balancer (ALB) response with multi-value headers. 'multiValueHeaders' is used for headers that can have multiple values. ```javascript { statusCode: 200, headers: { 'content-type': 'application/json', 'x-custom': 'value' }, multiValueHeaders: { 'content-type': ['application/json'], 'x-custom': ['value'], 'set-cookie': ['sessionId=abc123'] }, isBase64Encoded: false } ``` -------------------------------- ### Query Parameter Example: Multi-Value (API Gateway v2.0) Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Shows how multi-value query parameters are handled in API Gateway v2.0 when `parseCommaSeparatedQueryParams` is enabled. Fastify parses comma-separated values into an array. ```text Event.version: '2.0' Event.queryStringParameters: { foo: 'qux,bar' } Event.parseCommaSeparatedQueryParams: true Result: { foo: ['qux', 'bar'] } ``` -------------------------------- ### API Gateway v2.0 Response with Cookies Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of an API Gateway v2.0 response including cookies. Cookies are provided as an array of strings. ```javascript { statusCode: 200, headers: { 'content-type': 'application/json' }, body: '{"data":"value"}', isBase64Encoded: false, cookies: [ 'sessionId=abc123; Path=/', 'preferences=dark; Path=/; Secure' ] } ``` -------------------------------- ### Fastify Compress Plugin Integration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Example demonstrating how @fastify/aws-lambda automatically detects compression when using the @fastify/compress plugin. Responses with 'Content-Encoding: gzip' or 'br' are automatically base64-encoded without needing explicit configuration. ```javascript const compress = require('@fastify/compress') const awsLambdaFastify = require('@fastify/aws-lambda') const app = fastify() app.register(compress, { global: true, encodings: ['br', 'gzip'] }) app.get('/', (request, reply) => { reply.send({ data: Array(10000).fill('x') }) }) // No enforceBase64 needed — compression is auto-detected const proxy = awsLambdaFastify(app) // Responses with Content-Encoding: gzip or br automatically base64-encoded ``` -------------------------------- ### LambdaResponseStreamed Usage Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/types.md Demonstrates how to use `LambdaResponseStreamed` with `awsLambdaFastify` configured for streaming. It shows how to process the `meta` and `stream` objects, including integration with Lambda's `HttpResponseStream`. ```javascript const proxy = awsLambdaFastify(app, { payloadAsStream: true }) const { meta, stream } = await proxy(event, context) // meta structure: // { // statusCode: 200, // headers: { 'content-type': 'application/json' }, // isBase64Encoded: false, // cookies: undefined // } // stream: Node.js Readable stream // Typical usage with Lambda's streamifyResponse: const { HttpResponseStream } = awslambda responseStream = HttpResponseStream.from(responseStream, meta) await pipeline(stream, responseStream) ``` -------------------------------- ### Base64 Encoded Binary Response Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of a binary response encoded in Base64. The 'isBase64Encoded' field must be set to true. ```javascript { statusCode: 200, headers: { 'content-type': 'image/png', 'content-length': '1024' }, body: 'iVBORw0KGgoAAAANSUhEUgAAAAUA...', // base64 isBase64Encoded: true } ``` -------------------------------- ### Fastify App Definition Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md Defines a basic Fastify application with a root GET route. Exports the app for use in AWS Lambda or listens locally if run directly. ```javascript const fastify = require('fastify') const app = fastify() app.get('/', (request, reply) => reply.send({ hello: 'world' })) if (require.main === module) { // called directly i.e. "node app" app.listen({ port: 3000 }, (err) => { if (err) console.error(err) console.log('server listening on 3000') }) } else { // required as a module => executed on aws lambda module.exports = app } ``` -------------------------------- ### API Gateway v1.0 Response with Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of an API Gateway v1.0 response supporting multi-value headers. Headers that can have multiple values are specified in 'multiValueHeaders'. ```javascript { statusCode: 200, headers: { 'content-type': 'application/json', 'x-custom': 'value1,value2' // joined with comma }, multiValueHeaders: { 'set-cookie': [ 'sessionId=abc123; Path=/', 'preferences=dark; Path=/' ], 'x-multi': ['val1', 'val2'] }, isBase64Encoded: false } ``` -------------------------------- ### Default Binary Response Handling with Compression Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md This example demonstrates how compressed responses are automatically handled for API Gateway. The default behavior of @fastify/aws-lambda base64-encodes responses with non-identity Content-Encoding, such as gzip or br, without requiring additional configuration. ```javascript const fastify = require('fastify') const compress = require('@fastify/compress') const awsLambdaFastify = require('@fastify/aws-lambda') const app = fastify() app.register(compress, { global: true, encodings: ['br', 'gzip'] }) app.get('/', (req, reply) => reply.send({ hello: 'world' })) // Responses gain Content-Encoding: br|gzip, and the default behaviour // auto-base64-encodes them for API Gateway. No extra option needed. exports.handler = awsLambdaFastify(app) ``` -------------------------------- ### Fastify with Streaming Responses in AWS Lambda Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/INDEX.md Enable streaming for responses in AWS Lambda by setting `payloadAsStream: true`. This example demonstrates how to pipe the response stream to the Lambda response stream. ```javascript const { promisify } = require('util') const stream = require('stream') const pipeline = promisify(stream.pipeline) const proxy = awsLambdaFastify(app, { payloadAsStream: true }) exports.handler = awslambda.streamifyResponse( async (event, responseStream, context) => { const { meta, stream } = await proxy(event, context) responseStream = awslambda.HttpResponseStream.from(responseStream, meta) await pipeline(stream, responseStream) } ) ``` -------------------------------- ### API Gateway v2.0 (HTTP API) Event Object Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/request-decoration.md This example shows the event object structure for API Gateway v2.0 (HTTP API) integrations. It includes fields like version, routeKey, rawPath, rawQueryString, headers, query parameters, path parameters, and request context, differing slightly from the v1.0 structure. ```javascript { version: '2.0', routeKey: 'GET /users/{id}', rawPath: '/users/123', rawQueryString: 'filter=active&sort=name', headers: { 'host': 'api.example.com', 'x-custom-header': 'value' }, queryStringParameters: { 'filter': 'active', 'sort': 'name' }, pathParameters: { 'id': '123' }, requestContext: { http: { method: 'GET', path: '/users/123', protocol: 'HTTP/1.1', sourceIp: '203.0.113.1', userAgent: 'curl/7.64.1' }, routeKey: 'GET /users/{id}', timestamp: 1591096824769, requestId: 'a1b2c3d4-e5f6-11ea-8d87-362b9e155667', accountId: '123456789012', stage: 'prod', domainName: 'api.example.com' }, body: null, isBase64Encoded: false } ``` -------------------------------- ### AWS Lambda Fastify Option Validation Example Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Demonstrates how invalid option types are silently ignored by the library. Use TypeScript or manual validation to prevent unexpected runtime behavior. ```javascript // binaryMimeTypes expects string[], but string given { binaryMimeTypes: 'application/octet-stream' // Not validated } // This option is effectively ignored; behavior is as if empty array ``` -------------------------------- ### Configuration with Binary Response Support Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Enable binary response support by providing a list of MIME types that should be treated as binary. This is crucial for serving non-textual content like images or PDFs. ```javascript awsLambdaFastify(app, { binaryMimeTypes: [ 'application/octet-stream', 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf', 'application/zip', 'video/mp4' ] }) ``` -------------------------------- ### Streamed Response Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of a streamed response when payloadAsStream is true. The response includes metadata and a readable stream object. ```javascript { meta: { statusCode: 200, headers: { 'content-type': 'application/json' }, isBase64Encoded: false }, stream: } ``` -------------------------------- ### Standard JSON Response Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Example of a standard JSON response when payloadAsStream is false. Includes status code, headers, and stringified body. ```javascript { statusCode: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'content-length': '17', 'connection': 'keep-alive', 'date': 'Mon, 15 Jan 2024 12:34:56 GMT' }, body: '{"hello":"world"}', isBase64Encoded: false } ``` -------------------------------- ### Directory Structure Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/MANIFEST.md Lists the main directories and files within the documentation structure. ```text output/ ├── README.md (Master overview and navigation) ├── INDEX.md (Complete index and troubleshooting) ├── MANIFEST.md (This file) ├── types.md (Type definitions reference) ├── configuration.md (Configuration options guide) ├── event-handling.md (Event transformation pipeline) ├── response-handling.md (Response transformation pipeline) ├── request-decoration.md (Lambda context access guide) ├── binary-responses.md (Binary response handling guide) ├── module-graph.md (Architecture and module structure) └── api-reference/ └── awslambdafastify.md (Main function reference) ``` -------------------------------- ### Configure AWS Lambda Fastify for Binary Responses Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Initializes the awsLambdaFastify proxy with configuration for handling binary responses. It specifies MIME types for binary data and provides custom logic for enforcing base64 encoding, including debug logging. ```javascript const proxy = awsLambdaFastify(app, { binaryMimeTypes: ['image/png', 'image/jpeg'], enforceBase64: (res) => { const shouldEncode = customLogic(res) if (process.env.DEBUG_BINARY) { console.log(`Base64 encoding: ${shouldEncode}`) } return shouldEncode } }) ``` -------------------------------- ### Response Streaming with `payloadAsStream` Source: https://github.com/fastify/aws-lambda-fastify/blob/main/README.md Enables response streaming in AWS Lambda by setting `payloadAsStream: true`. This example uses `stream.pipeline` to pipe the response stream. ```javascript import awsLambdaFastify from '@fastify/aws-lambda' import { promisify } from 'node:util' import stream from 'node:stream' import app from './app.js' const pipeline = promisify(stream.pipeline) const proxy = awsLambdaFastify(app, { payloadAsStream: true }) export const handler = awslambda.streamifyResponse(async (event, responseStream, context) => { const { meta, stream } = await proxy(event, context) responseStream = awslambda.HttpResponseStream.from(responseStream, meta) await pipeline(stream, responseStream) }) await app.ready() // https://github.com/fastify/aws-lambda-fastify/issues/89 ``` -------------------------------- ### Configure Binary MIME Types for Audio and Video Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Specify audio and video MIME types in the `binaryMimeTypes` array to ensure they are handled correctly as binary data. ```javascript binaryMimeTypes: [ 'audio/mpeg', 'audio/wav', 'video/mp4', 'video/webm', 'video/quicktime' ] ``` -------------------------------- ### ALB Integration Configuration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Configure the library for integration with Application Load Balancer (ALB). This preset enables multi-value headers, which is a common ALB feature. ```javascript awsLambdaFastify(app, { albMultiValueHeaders: true, serializeLambdaArguments: false, decorateRequest: true }) ``` -------------------------------- ### File Dependencies Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/MANIFEST.md This section details the file dependencies within the project, illustrating how different markdown files relate to each other. ```markdown README.md ├── requires INDEX.md ├── requires api-reference/awslambdafastify.md └── requires configuration.md INDEX.md ├── references all other files └── depends on README.md for overview configuration.md ├── references types.md └── references INDEX.md for presets event-handling.md ├── references configuration.md (options) └── references request-decoration.md (decoration) response-handling.md ├── references binary-responses.md ├── references configuration.md (options) └── references types.md (response types) api-reference/awslambdafastify.md ├── references types.md ├── references configuration.md └── references request-decoration.md module-graph.md ├── references event-handling.md ├── references response-handling.md └── references types.md binary-responses.md ├── references configuration.md └── references response-handling.md request-decoration.md ├── references configuration.md └── references event-handling.md ``` -------------------------------- ### CommonJS Export and Usage Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/module-graph.md Demonstrates how to export the aws-lambda-fastify module using CommonJS and how to integrate it into an AWS Lambda handler. ```APIDOC ## CommonJS Export ### Export ```javascript // index.js module.exports = (app, options) => { ... } module.exports.default = module.exports module.exports.awsLambdaFastify = module.exports ``` ### Usage ```javascript const awsLambdaFastify = require('@fastify/aws-lambda') const handler = awsLambdaFastify(app) ``` ``` -------------------------------- ### Custom Base64 Encoding Logic Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Provide a custom function to determine if a response should be base64-encoded, replacing default content-encoding detection. This example checks for compression and a custom header. ```javascript { enforceBase64: (res) => { // Custom logic: check for compression const enc = res.headers['content-encoding'] if (enc && enc !== 'identity') return true // Also check for a custom header if (res.headers['x-binary'] === 'true') return true return false } } ``` -------------------------------- ### Application Load Balancer Configuration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/INDEX.md Configure aws-lambda-fastify for Application Load Balancer, enabling multi-value headers. ```javascript awsLambdaFastify(app, { albMultiValueHeaders: true, decorateRequest: true }) ``` -------------------------------- ### Get Remaining Lambda Execution Time Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/request-decoration.md Use the `getRemainingTimeInMillis()` method to determine the number of milliseconds left before the Lambda function times out. This is useful for managing long-running operations. ```javascript context.getRemainingTimeInMillis() ``` -------------------------------- ### Fastify Inject Method Parameters Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md This shows the parameters available for the `app.inject` method, including HTTP method, URL, query, payload, headers, and remote address. The `payloadAsStream` option enables streaming for the payload. ```javascript app.inject({ method, url, query, payload, headers, remoteAddress, payloadAsStream: options.payloadAsStream }, callback) ``` -------------------------------- ### Configure ALB Binary MIME Types Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Configure aws-lambda-fastify for ALB by specifying binary MIME types and enabling multi-value headers. ```javascript const proxy = awsLambdaFastify(app, { binaryMimeTypes: [ 'image/png', 'image/jpeg', 'application/pdf', 'application/octet-stream' ], albMultiValueHeaders: true, // Let compression detection work automatically }) ``` -------------------------------- ### Process Basic Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/event-handling.md Initializes the headers object by copying all headers from `event.headers`. ```javascript const headers = Object.assign({}, event.headers) ``` -------------------------------- ### Strip API Gateway Stage from URL Path Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Configure whether to include the API Gateway stage in the request path. When `false`, the stage is stripped if it appears at the start of the URL and is not part of the `resourcePath`. ```javascript { retainStage: false } ``` -------------------------------- ### Fastify with Binary Responses in AWS Lambda Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/INDEX.md Configure the aws-lambda adapter to handle binary responses by specifying MIME types. This is useful for serving images, PDFs, or other non-textual content. ```javascript const proxy = awsLambdaFastify(app, { binaryMimeTypes: ['image/png', 'image/jpeg', 'application/pdf'] }) exports.handler = proxy ``` -------------------------------- ### ALB (Application Load Balancer) Event Object Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/request-decoration.md This is an example of the event object structure when using AWS Lambda with an Application Load Balancer (ALB). It contains essential request details and information specific to the ALB target group. ```javascript { version: '2.0', requestContext: { http: { method: 'GET', path: '/health', protocol: 'HTTP/1.1', sourceIp: '10.0.0.1' }, elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' } }, rawPath: '/health', rawQueryString: '', headers: { 'host': 'internal-alb.example.com', 'user-agent': 'ELB-HealthChecker/2.0' }, body: null, isBase64Encoded: false } ``` -------------------------------- ### Initialize AWS Lambda Fastify Handler Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/INDEX.md Import and initialize the awsLambdaFastify handler with Fastify. Configure options like `payloadAsStream` for streaming support. The handler is typed as `PromiseHandler` for AWS Lambda responses. ```typescript import awsLambdaFastify from '@fastify/aws-lambda' import { FastifyInstance } from 'fastify' const app: FastifyInstance = fastify() const handler = awsLambdaFastify(app, { payloadAsStream: true }) // handler is PromiseHandler ``` -------------------------------- ### Configure Streaming Mode with Lambda Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Sets up AWS Lambda Fastify to use streaming mode for responses, wrapping the response in a specific structure and integrating with Lambda's streamifyResponse for efficient handling of large payloads. ```javascript const proxy = awsLambdaFastify(app, { payloadAsStream: true }) exports.handler = awslambda.streamifyResponse( async (event, responseStream, context) => { const { meta, stream } = await proxy(event, context) const httpResponseStream = awslambda.HttpResponseStream.from(responseStream, meta) await pipeline(stream, httpResponseStream) } ) ``` -------------------------------- ### API Gateway v1.0 (REST API) Event Object Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/request-decoration.md This is an example of the event object structure when using API Gateway v1.0 (REST API) with AWS Lambda. It includes details about the resource, path, HTTP method, headers, query parameters, path parameters, stage variables, request context, and body. ```javascript { resource: '/users/{id}', path: '/users/123', httpMethod: 'GET', headers: { 'Host': 'api.example.com', 'X-Custom-Header': 'value' }, multiValueHeaders: { 'X-Multi': ['value1', 'value2'] }, queryStringParameters: { 'filter': 'active' }, multiValueQueryStringParameters: { 'tags': ['a', 'b', 'c'] }, pathParameters: { 'id': '123' }, stageVariables: { 'env': 'prod' }, requestContext: { resourceId: 'xyz123', resourcePath: '/users/{id}', httpMethod: 'GET', extendedRequestId: 'req-id', requestTime: '09/Apr/2015:12:34:56 +0000', path: '/prod/users/123', accountId: '123456789012', protocol: 'HTTP/1.1', stage: 'prod', domainPrefix: 'api', requestTimeEpoch: 1428582896000, requestId: 'c6af9ac6-7b61-11e6-9a41-93e8deadbeef', identity: { sourceIp: '203.0.113.1' }, domain: 'api.example.com' }, body: null, isBase64Encoded: false } ``` -------------------------------- ### Set-Cookie Processing for API Gateway v2.0 Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Demonstrates how multiple 'Set-Cookie' headers from Fastify are processed into a 'cookies' array for API Gateway v2.0. ```javascript reply.header('Set-Cookie', 'session=abc123') reply.header('Set-Cookie', 'theme=dark') ``` ```javascript { cookies: ['session=abc123', 'theme=dark'], headers: { // Set-Cookie removed from headers } } ``` -------------------------------- ### Configure Binary MIME Types for Images Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Specify image MIME types in the `binaryMimeTypes` array to ensure they are handled correctly as binary data. ```javascript binaryMimeTypes: [ 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml', 'image/x-icon' ] ``` -------------------------------- ### Handling Compressed Responses Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/INDEX.md Integrate @fastify/compress with aws-lambda-fastify to automatically handle compressed responses. ```javascript const compress = require('@fastify/compress') const app = fastify() app.register(compress, { global: true }) // Compression auto-detected and base64-encoded awsLambdaFastify(app) ``` -------------------------------- ### Fastify Lambda with Callback Pattern Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/api-reference/awslambdafastify.md Integrate Fastify with AWS Lambda using the callback pattern. This approach is an alternative to the promise-based handler. ```javascript const proxy = awsLambdaFastify(app) exports.handler = (event, context, callback) => { proxy(event, context, callback) } ``` -------------------------------- ### Standard API Gateway v2.0 Configuration Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Use this preset for standard API Gateway v2.0 integrations. It configures common options for this event source. ```javascript awsLambdaFastify(app, { decorateRequest: true, serializeLambdaArguments: false, parseCommaSeparatedQueryParams: true, retainStage: false, payloadAsStream: false }) ``` -------------------------------- ### Configure Binary MIME Types for Archives Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Specify archive MIME types in the `binaryMimeTypes` array to ensure they are handled correctly as binary data. ```javascript binaryMimeTypes: [ 'application/zip', 'application/gzip', 'application/x-tar', 'application/x-rar-compressed', 'application/x-7z-compressed' ] ``` -------------------------------- ### Configure Binary MIME Types Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Specify MIME types that should be base64-encoded in the response. The handler checks the response Content-Type header against this list. ```javascript { binaryMimeTypes: [ 'application/octet-stream', 'image/png', 'image/jpeg', 'image/gif', 'application/pdf', 'application/zip' ] } ``` -------------------------------- ### Enable ALB Multi-Value Headers Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Enable support for ALB (Application Load Balancer) multi-value header format. When enabled, all response headers are converted to multi-value format in `multiValueHeaders`, with each header becoming an array containing a single element. This is useful as ALB requires headers in multi-value format. ```javascript { albMultiValueHeaders: true } ``` -------------------------------- ### Configure Binary MIME Types for Documents Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Specify document MIME types in the `binaryMimeTypes` array to ensure they are handled correctly as binary data. ```javascript binaryMimeTypes: [ 'application/pdf', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ] ``` -------------------------------- ### Configure Streaming Responses Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Configure aws-lambda-fastify to handle streaming responses, disabling base64 encoding when payloadAsStream is true. ```javascript const proxy = awsLambdaFastify(app, { payloadAsStream: true, disableBase64Encoding: true // Streams are handled by Lambda, not base64 }) ``` -------------------------------- ### Fastify Lambda with Custom Binary Types and Options Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/api-reference/awslambdafastify.md Configure the awsLambdaFastify handler with custom binary MIME types and other options like `decorateRequest`. This is useful for handling non-JSON binary responses. ```javascript exports.handler = awsLambdaFastify(app, { binaryMimeTypes: ['application/octet-stream', 'image/png', 'image/jpeg'], decorateRequest: true }) ``` -------------------------------- ### Configure Generic Binary MIME Types Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/binary-responses.md Specify generic binary MIME types in the `binaryMimeTypes` array to ensure they are handled correctly as binary data. ```javascript binaryMimeTypes: [ 'application/octet-stream', 'application/x-protobuf' ] ``` -------------------------------- ### Set-Cookie Processing for API Gateway v1.0 Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/response-handling.md Shows how multiple 'Set-Cookie' headers from Fastify are mapped to 'multiValueHeaders' for API Gateway v1.0. ```javascript reply.header('Set-Cookie', 'session=abc123') reply.header('Set-Cookie', 'theme=dark') ``` ```javascript { headers: { // No Set-Cookie in headers }, multiValueHeaders: { 'set-cookie': ['session=abc123', 'theme=dark'] } } ``` -------------------------------- ### Enable Serialization of Lambda Arguments Source: https://github.com/fastify/aws-lambda-fastify/blob/main/_autodocs/configuration.md Set serializeLambdaArguments to true to encode event and context as URL-encoded headers instead of decorating the request object. ```javascript { serializeLambdaArguments: true } ```