### Install Local Dependencies and Setup Pre-commit Hooks Source: https://docs.aws.amazon.com/powertools/typescript/latest/contributing/setup Run this command to install all necessary local dependencies and configure pre-commit hooks for contributing to the project. ```bash npm run setup-local ``` -------------------------------- ### Setup Local Documentation Environment with Python Source: https://docs.aws.amazon.com/powertools/typescript/latest/contributing/setup Create a Python virtual environment and install the necessary dependencies to run the documentation website locally without Docker. ```bash npm run docs:local:setup ``` -------------------------------- ### Example Log Output with Lambda Context Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_logger.html An example of a structured log output after injecting Lambda context. It includes details like cold start status, function details, and trace ID. ```json { "cold_start": true, "function_arn": "arn:aws:lambda:eu-west-1:123456789012:function:shopping-cart-api-lambda-prod-eu-west-1", "function_memory_size": 128, "function_request_id": "c6af9ac6-7b61-11e6-9a41-93e812345678", "function_name": "shopping-cart-api-lambda-prod-eu-west-1", "level": "INFO", "message": "This is an INFO log with some context", "service": "serverlessAirline", "timestamp": "2021-12-12T21:21:08.921Z", "xray_trace_id": "abcdef123456abcdef123456abcdef123456" } ``` -------------------------------- ### Install Kafka with Protobuf Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Kafka utility and its dependency, protobufjs. ```bash npm i @aws-lambda-powertools/kafka protobufjs ``` -------------------------------- ### Install Metrics Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Metrics utility using npm. ```bash npm i @aws-lambda-powertools/metrics ``` -------------------------------- ### Using logMetrics Middleware with Middy.js Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/functions/_aws-lambda-powertools_metrics.middleware_middy.logMetrics.html This example demonstrates how to integrate the logMetrics middleware into a Middy.js handler. It shows the setup for the Metrics instance and how to apply the middleware with custom options like capturing cold start metrics and throwing errors on empty metrics. ```typescript import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics'; import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; import middy from '@middy/core'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); export const handler = middy(async (event) => { metrics.addMetadata('request_id', event.requestId); metrics.addMetric('successfulBooking', MetricUnit.Count, 1); }).use(logMetrics(metrics, { captureColdStartMetric: true, throwOnEmptyMetrics: true, })); ``` -------------------------------- ### Utility.isColdStart() Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_metrics.index._internal_.Utility.html An alias for `getColdStart()`, this method provides a more readable way to check for cold start conditions. It returns true on the first invocation and false on subsequent ones, allowing for conditional execution of code specific to the initial Lambda environment setup. ```APIDOC ## Utility.isColdStart() ### Description This method is an alias of `getColdStart()` and is exposed for convenience and better readability in certain usages. It checks if the current Lambda function invocation is a cold start. ### Method Signature `isColdStart(): boolean` ### Returns - `boolean`: `true` if it's a cold start, `false` otherwise. ### Example ```typescript import { Utility } from '@aws-lambda-powertools/commons'; const utility = new Utility(); export const handler = async (_event: any, _context: any) => { if (utility.isColdStart()) { // do something, this block is only executed on the first invocation of the function } else { // do something else, this block gets executed on all subsequent invocations } }; ``` ``` -------------------------------- ### Install @aws-lambda-powertools/commons Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_commons.html Install the utility by running this command in your project. ```bash npm i @aws-lambda-powertools/commons Copy ``` -------------------------------- ### Install Parameters with SSM Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Parameters utility and its required AWS SDK client for SSM. ```bash npm i @aws-lambda-powertools/parameters @aws-sdk/client-ssm ``` -------------------------------- ### Install Kafka with Avro Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Kafka utility and its dependency, avro-js. ```bash npm i @aws-lambda-powertools/kafka avro-js ``` -------------------------------- ### Install Idempotency with Valkey Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt Install the Idempotency utility along with the Valkey client for cache persistence. ```bash npm i @aws-lambda-powertools/idempotency @valkey/valkey-glide ``` -------------------------------- ### Install Parameters and AWS SDK for DynamoDB Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_parameters.html Install the necessary libraries for using the DynamoDB parameter provider. ```bash npm install @aws-lambda-powertools/parameters @aws-sdk/client-dynamodb @aws-sdk/util-dynamodb ``` -------------------------------- ### Install Parameters and AWS SDK for AppConfig Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_parameters.html Install the necessary libraries for using the AppConfig parameter provider. ```bash npm install @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata ``` -------------------------------- ### Install Kafka Utility Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt Install the core Kafka utility package using npm. ```bash npm install @aws-lambda-powertools/kafka ``` -------------------------------- ### Install Parameters with AppConfig Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Parameters utility and its required AWS SDK client for AppConfig. ```bash npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata ``` -------------------------------- ### Install Idempotency with Redis Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt Install the Idempotency utility along with the Redis client for cache persistence. ```bash npm i @aws-lambda-powertools/idempotency @redis/client ``` -------------------------------- ### Install Tracer Module Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_tracer.html Install the @aws-lambda-powertools/tracer package using npm. ```bash npm i @aws-lambda-powertools/tracer ``` -------------------------------- ### Install Validation with AJV Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Validation utility and its default dependency, AJV. ```bash npm i @aws-lambda-powertools/validation ``` -------------------------------- ### Install Tracer Package Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt Install the @aws-lambda-powertools/tracer package as a peer dependency. ```bash npm install @aws-lambda-powertools/tracer ``` -------------------------------- ### Install Idempotency with DynamoDB Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Idempotency utility and its required AWS SDK clients for DynamoDB. ```bash npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ``` -------------------------------- ### Install Parser and Zod Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_parser.html Install the @aws-lambda-powertools/parser and zod libraries to begin using the parser utility. ```bash npm install @aws-lambda-powertools/parser zod ``` -------------------------------- ### Run Documentation Website with Python Source: https://docs.aws.amazon.com/powertools/typescript/latest/contributing/setup Start the documentation website and API reference locally using Python after setting up the environment. ```bash npm run docs:local:run ``` -------------------------------- ### Example HTTP GET Request Event Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/event-handler/http This is an example of an HTTP GET request event payload that the router might process. ```json { "resource": "/logo", "path": "/logo", "httpMethod": "GET" } ``` -------------------------------- ### Run Documentation Website with Docker Source: https://docs.aws.amazon.com/powertools/typescript/latest/contributing/setup Start the documentation website and API reference locally using the pre-built Docker image. ```bash npm run docs:docker:run ``` -------------------------------- ### Example Middleware Returning Early with cleanupMiddlewares Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/functions/_aws-lambda-powertools_commons.middleware_cleanupMiddlewares.cleanupMiddlewares.html Demonstrates how to use the cleanupMiddlewares function within a custom Middy middleware. This example shows a middleware that returns early for GET requests, ensuring Powertools resources are cleaned up before exiting. ```typescript import middy from '@middy/core'; import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; // Example middleware that returns early const myCustomMiddleware = (): middy.MiddlewareObj => { const before = async (request: middy.Request): Promise => { // If the request is a GET, return early (as an example) if (request.event.httpMethod === 'GET') { // Cleanup Powertools resources await cleanupMiddlewares(request); // Then return early return 'GET method not supported'; } }; return { before, }; }; ``` -------------------------------- ### prepare Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index.BasePartialBatchProcessor.html Sets up the processor with the initial state, preparing it for processing. ```APIDOC ## prepare ### Description Set up the processor with the initial state ready for processing. ### Method N/A (Method of a class) ### Returns void ``` -------------------------------- ### Kafka Consumer with Avro Schema Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_kafka.html This example demonstrates processing Kafka messages using Avro schema deserialization. Install 'avro-js' and ensure the schema file is accessible. ```typescript import { readFileSync } from 'node:fs'; import { SchemaType, kafkaConsumer } from '@aws-lambda-powertools/kafka'; import type { SchemaConfig } from '@aws-lambda-powertools/kafka/types'; import { Logger } from '@aws-lambda-powertools/logger'; const logger = new Logger({ serviceName: 'kafka-consumer' }); const schemaConfig = { value: { type: SchemaType.AVRO, schema: readFileSync(new URL('./user.avsc', import.meta.url), 'utf8'), }, } satisfies SchemaConfig; export const handler = kafkaConsumer(async (event, _context) => { for (const { value } of event.records) { logger.info('received value', { value }); } }, schemaConfig); ``` -------------------------------- ### prepare Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index.SqsFifoPartialProcessorAsync.html Sets up the processor with the initial state, preparing it for processing. ```APIDOC ## prepare ### Description Set up the processor with the initial state ready for processing ### Returns void ``` -------------------------------- ### Kafka Consumer with JSON Schema and Zod Parsing Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_kafka.html This example shows how to deserialize Kafka messages using JSON schema and then parse them with Zod for validation. Ensure 'zod' is installed. ```typescript import { SchemaType, kafkaConsumer } from '@aws-lambda-powertools/kafka'; import type { SchemaConfig } from '@aws-lambda-powertools/kafka/types'; import { Logger } from '@aws-lambda-powertools/logger'; import { z } from 'zod/v4'; const logger = new Logger({ serviceName: 'kafka-consumer' }); const OrderItemSchema = z.object({ productId: z.string(), quantity: z.number().int().positive(), price: z.number().positive(), }); const OrderSchema = z.object({ id: z.string(), customerId: z.string(), items: z.array(OrderItemSchema).min(1, 'Order must have at least one item'), createdAt: z.iso.datetime(), totalAmount: z.number().positive(), }); const schemaConfig = { value: { type: SchemaType.JSON, parserSchema: OrderSchema, }, } satisfies SchemaConfig; export const handler = kafkaConsumer>( async (event, _context) => { for (const record of event.records) { const { value: { id, items }, } = record; logger.setCorrelationId(id); logger.debug(`order includes ${items.length} items`); } }, schemaConfig ); ``` -------------------------------- ### Instantiate Logger in Lambda Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/logger Instantiate the Logger utility outside the Lambda handler to reuse resources across invocations and track cold starts. This example logs a simple 'Hello World' message. ```typescript import { Logger } from '@aws-lambda-powertools/logger'; const logger = new Logger({ serviceName: 'serverlessAirline' }); export const handler = async () => { logger.info('Hello World'); }; ``` -------------------------------- ### Configure Metrics with logMetrics Decorator Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/interfaces/_aws-lambda-powertools_metrics.types.MetricsInterface.html Example of configuring the Metrics class and using the @metrics.logMetrics decorator to automatically capture cold start metrics. Ensure the LambdaInterface is correctly implemented and the handler is bound. ```typescript import { Metrics } from '@aws-lambda-powertools/metrics'; import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); class Lambda implements LambdaInterface { ⁣@metrics.logMetrics({ captureColdStartMetric: true }) public handler(_event: unknown, _context: unknown) { // ... } } const handlerClass = new Lambda(); export const handler = handlerClass.handler.bind(handlerClass); ``` -------------------------------- ### Custom Persistence Layer Implementation Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/idempotency Example implementation of a custom persistence layer using a generic key-value store. This class extends BasePersistenceLayer and overrides methods for getting, putting, updating, and deleting records. ```typescript import { IdempotencyItemAlreadyExistsError, IdempotencyItemNotFoundError, IdempotencyRecordStatus, } from '@aws-lambda-powertools/idempotency'; import { BasePersistenceLayer, IdempotencyRecord, } from '@aws-lambda-powertools/idempotency/persistence'; import type { IdempotencyRecordOptions } from '@aws-lambda-powertools/idempotency/types'; import { Transform } from '@aws-lambda-powertools/parameters'; import { getSecret } from '@aws-lambda-powertools/parameters/secrets'; import { ProviderClient, ProviderItemAlreadyExists, } from './advancedBringYourOwnPersistenceLayerProvider'; import type { ApiSecret, ProviderItem } from './types'; class CustomPersistenceLayer extends BasePersistenceLayer { #collectionName: string; #client?: ProviderClient; public constructor(config: { collectionName: string }) { super(); this.#collectionName = config.collectionName; } protected async _deleteRecord(record: IdempotencyRecord): Promise { await (await this.#getClient()).delete( this.#collectionName, record.idempotencyKey ); } protected async _getRecord( idempotencyKey: string ): Promise { try { const item = await (await this.#getClient()).get( this.#collectionName, idempotencyKey ); return new IdempotencyRecord({ ...(item as unknown as IdempotencyRecordOptions), }); } catch (error) { throw new IdempotencyItemNotFoundError('Item not found in store', { cause: error, }); } } protected async _putRecord(record: IdempotencyRecord): Promise { const item: Partial = { status: record.getStatus(), }; if (record.inProgressExpiryTimestamp !== undefined) { item.in_progress_expiration = record.inProgressExpiryTimestamp; } if (this.isPayloadValidationEnabled() && record.payloadHash !== undefined) { item.validation = record.payloadHash; } const ttl = record.expiryTimestamp ? Math.floor(new Date(record.expiryTimestamp * 1000).getTime() / 1000) - Math.floor(Date.now() / 1000) : this.getExpiresAfterSeconds(); let existingItem: ProviderItem | undefined; try { existingItem = await (await this.#getClient()).put( this.#collectionName, record.idempotencyKey, item, { ttl, } ); } catch (error) { if (error instanceof ProviderItemAlreadyExists) { if ( existingItem && existingItem.status !== IdempotencyRecordStatus.INPROGRESS && (existingItem.in_progress_expiration || 0) < Date.now() ) { throw new IdempotencyItemAlreadyExistsError( `Failed to put record for already existing idempotency key: ${record.idempotencyKey}` ); } } } } protected async _updateRecord(record: IdempotencyRecord): Promise { const value: Partial = { data: JSON.stringify(record.responseData), status: record.getStatus(), }; if (this.isPayloadValidationEnabled()) { value.validation = record.payloadHash; } await (await this.#getClient()).update( this.#collectionName, record.idempotencyKey, value ); } async #getClient(): Promise { if (this.#client) return this.#client; const secretName = process.env.API_SECRET; ``` -------------------------------- ### Initialize Tracer and Create Subsegments Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/tracer Instantiate the Tracer utility outside the Lambda handler for resource reuse. This example shows how to get the current segment, add a new subsegment, and attach annotations and metadata to it. ```typescript import { Tracer } from '@aws-lambda-powertools/tracer'; const tracer = new Tracer({ serviceName: 'serverlessAirline' }); export const handler = async () => { const segment = tracer.getSegment(); const subsegment = segment?.addNewSubsegment('subsegment'); subsegment?.addAnnotation('annotationKey', 'annotationValue'); subsegment?.addMetadata('metadataKey', { foo: 'bar' }); subsegment?.close(); }; ``` -------------------------------- ### Initialize Metrics with Options Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/types/_aws-lambda-powertools_metrics.types.MetricsOptions.html Demonstrates how to instantiate the Metrics class with various configuration options. Ensure you have imported the Metrics class. ```typescript import { Metrics } from '@aws-lambda-powertools/metrics'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders', singleMetric: true, }); ``` -------------------------------- ### Define and Use Typed Stores Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/event-handler/http This example demonstrates how to define a custom environment type 'AppEnv' for typed stores. It shows setting and getting values from both request context and shared stores, including type-checking for unknown keys. ```typescript import { Router } from '@aws-lambda-powertools/event-handler/http'; import type { Context } from 'aws-lambda'; type AppEnv = { store: { request: { userId: string; isAdmin: boolean }; shared: { db: { query: (sql: string) => Promise } }; }; }; const app = new Router(); // Shared store is typed — only accepts keys defined in AppEnv app.shared.set('db', createDbClient()); app.use(async ({ reqCtx, next }) => { const auth = reqCtx.req.headers.get('Authorization') ?? ''; const { sub, isAdmin } = jwt.verify(auth.replace('Bearer ', ''), 'secret'); reqCtx.set('userId', sub); reqCtx.set('isAdmin', isAdmin); await next(); }); app.get('/profile', async (reqCtx) => { const userId = reqCtx.get('userId'); const db = reqCtx.shared.get('db'); // @ts-expect-error - 'email' is not a key defined in AppEnv reqCtx.get('email'); if (!userId || !db) return { error: 'not ready' }; return { userId }; }); export const handler = async (event: unknown, context: Context) => app.resolve(event, context); ``` -------------------------------- ### Automatically Flush Metrics with Middy Middleware Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/metrics Integrate the `logMetrics` middleware from `@aws-lambda-powertools/metrics` with your Middy-wrapped Lambda handler to automatically validate, serialize, and flush metrics. This example shows the handler setup and the resulting CloudWatch Logs output. ```typescript import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics'; import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; import middy from '@middy/core'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders', }); const lambdaHandler = async ( _event: unknown, _context: unknown ): Promise => { metrics.addMetric('successfulBooking', MetricUnit.Count, 1); }; export const handler = middy(lambdaHandler).use(logMetrics(metrics)); ``` ```json { "successfulBooking": 1.0, "_aws": { "Timestamp": 1592234975665, "CloudWatchMetrics": [ { "Namespace": "serverlessAirline", "Dimensions": [["service"]], "Metrics": [ { "Name": "successfulBooking", "Unit": "Count" } ] } ] }, "service": "orders" } ``` -------------------------------- ### Process Kinesis Data Streams Batch Records Synchronously Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index.BatchProcessorSync.html Example demonstrating synchronous batch processing of Kinesis Data Streams records using BatchProcessorSync. It includes setup for partial failure handling via processPartialResponseSync. ```typescript import { BatchProcessorSync, EventType, processPartialResponseSync, } from '@aws-lambda-powertools/batch'; import type { KinesisStreamHandler, KinesisStreamRecord } from 'aws-lambda'; const processor = new BatchProcessorSync(EventType.KinesisDataStreams); const recordHandler = (record: KinesisStreamRecord): void => { const payload = JSON.parse(record.kinesis.data); }; export const handler: KinesisStreamHandler = async (event, context) => processPartialResponseSync(event, recordHandler, processor, { context, }); ``` -------------------------------- ### SqsFifoProcessorStore Constructor Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index._internal_.SqsFifoProcessorStore.html Initializes a new instance of the SqsFifoProcessorStore class. ```APIDOC ## SqsFifoProcessorStore() ### Description Initializes a new instance of the SqsFifoProcessorStore class. ### Returns - SqsFifoProcessorStore: A new instance of the SqsFifoProcessorStore. ``` -------------------------------- ### Asynchronous SQS FIFO Partial Batch Processing Example Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index.SqsFifoPartialProcessorAsync.html Demonstrates how to use SqsFifoPartialProcessorAsync with `processPartialResponse` to handle asynchronous SQS FIFO queue events. This setup allows for processing records and reporting partial failures while preserving order. ```typescript import { BatchProcessor, SqsFifoPartialProcessorAsync, processPartialResponse, } from '@aws-lambda-powertools/batch'; import type { SQSRecord, SQSHandler } from 'aws-lambda'; const processor = new SqsFifoPartialProcessorAsync(); const recordHandler = async (record: SQSRecord): Promise => { const payload = JSON.parse(record.body); }; export const handler: SQSHandler = async (event, context) => processPartialResponse(event, recordHandler, processor, { context, }); ``` -------------------------------- ### Get multiple SSM parameters by name Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/functions/_aws-lambda-powertools_parameters.ssm.getParametersByName.html This example demonstrates how to use `getParametersByName` to retrieve multiple SSM parameters. It shows how to apply different transformations to the parameter values, including default handling, JSON parsing, and binary data decoding. ```APIDOC ## getParametersByName ### Description Retrieves multiple AWS Systems Manager (SSM) parameters by their names. This function can apply transformations to the parameter values and offers configurable error handling. ### Method `getParametersByName(options: Record) => Promise>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `options` (Record) - An object where keys are the full parameter names (e.g., `/my-parameter-1`) and values are configuration objects for each parameter. Each configuration object can include a `transform` property to specify how the parameter value should be processed (e.g., 'json', 'binary'). ### Request Example ```typescript import { getParametersByName } from '@aws-lambda-powertools/parameters/ssm'; export const handler = async (): Promise => { const parameters = await getParametersByName({ '/my-parameter-1': {}, // Use default options (no transformation) '/my-parameter-2': { transform: 'json' }, // Parse the value as JSON '/my-parameter-3': { transform: 'binary' }, // Parse the value as base64-encoded binary data }); }; ``` ### Response #### Success Response Returns an object where keys are the parameter names and values are the retrieved and transformed parameter values. #### Response Example ```json { "/my-parameter-1": "parameter_value_1", "/my-parameter-2": {"key": "value"}, // Example if transform was 'json' "/my-parameter-3": "binary_data_string" // Example if transform was 'binary' } ``` ### Error Handling The `throwOnError` parameter (when using `SSMProvider` class directly) controls error handling. If `true` (default), it throws a `GetParameterError` on any failure. If `false`, it aggregates all failed parameters under an `_errors` key in the response. ``` -------------------------------- ### Build Documentation Docker Image Source: https://docs.aws.amazon.com/powertools/typescript/latest/contributing/setup Build the Docker image for running the documentation website and API reference locally. This command is only needed the first time. ```bash npm run docs:docker:build ``` -------------------------------- ### Install Kafka Consumer with Protobuf Support Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/kafka Install the Kafka consumer package along with the 'protobufjs' library for Protobuf schema validation and processing. ```bash npm install @aws-lambda-powertools/kafka protobufjs ``` -------------------------------- ### Custom Idempotency Persistence Layer Example Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt This snippet shows how to create a custom persistence store for idempotency. It requires implementing specific methods like get, put, and delete. Ensure your implementation handles record expiration and potential race conditions. ```typescript import { IdempotencyConfig, IdempotencyRecordStatusValue, makeIdempotent, } from '@aws-lambda-powertools/idempotency'; import type { Context } from 'aws-lambda'; import { randomUUID } from 'crypto'; // Define types for request, response, and subscription results export type Request = { user: string; productId: string; }; export type Response = { [key: string]: unknown; }; export type SubscriptionResult = { id: string; productId: string; }; // Placeholder for a custom persistence layer implementation class CustomPersistenceLayer { private collectionName: string; constructor(config: { collectionName: string }) { this.collectionName = config.collectionName; console.log(`Initialized custom persistence layer for collection: ${this.collectionName}`); } // Mock implementation for putRecord async putRecord(key: string, data: string, ttl: number): Promise { console.log(`Putting record: ${key} with data: ${data} and TTL: ${ttl}`); // In a real implementation, this would interact with a database (e.g., DynamoDB) // Ensure to handle potential conflicts and errors. } // Mock implementation for getRecord async getRecord(key: string): Promise<{ data: string; status: IdempotencyRecordStatusValue } | undefined> { console.log(`Getting record: ${key}`); // In a real implementation, this would fetch from a database. // Return undefined if the record does not exist or has expired. return undefined; // Placeholder } // Mock implementation for deleteRecord async deleteRecord(key: string): Promise { console.log(`Deleting record: ${key}`); // In a real implementation, this would remove from a database. } } // Instantiate the custom persistence store and configuration const persistenceStore = new CustomPersistenceLayer({ collectionName: 'powertools', }); const config = new IdempotencyConfig({ expiresAfterSeconds: 60, }); // Create an idempotent function for processing subscription payments const createSubscriptionPayment = makeIdempotent( async ( _transactionId: string, event: Request ): Promise => { // ... simulate creating a payment console.log('Processing payment for product:', event.productId); return { id: randomUUID(), productId: event.productId, }; }, { persistenceStore, dataIndexArgument: 1, // The 'event' object at index 1 is used as the idempotency key config, } ); // Lambda handler function export const handler = async ( event: Request, context: Context ): Promise => { config.registerLambdaContext(context); const transactionId = randomUUID(); console.log('Received event:', event); const payment = await createSubscriptionPayment(transactionId, event); return { paymentId: payment.id, message: 'success', statusCode: 200, }; }; ``` -------------------------------- ### Using logMetrics Middleware with Middy.js Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_metrics.html Integrates the `@logMetrics()` middleware with Middy.js to automatically flush metrics at the end of a Lambda function's execution. This example demonstrates configuring options like capturing cold start metrics and throwing an error if no metrics are added. ```typescript import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics'; import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; import middy from '@middy/core'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders', }); export const handler = middy(async (event) => { metrics.addMetadata('request_id', event.requestId); metrics.addMetric('successfulBooking', MetricUnit.Count, 1); }).use(logMetrics(metrics, { captureColdStartMetric: true, throwOnEmptyMetrics: true, })); ``` -------------------------------- ### Capturing Cold Start Metric Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_metrics.html Illustrates how to use the `captureColdStartMetric()` method to automatically record a 'ColdStart' metric when a Lambda function experiences a cold start. ```APIDOC ## Capturing Cold Start Metric ### Description This example demonstrates how to use the `captureColdStartMetric()` method provided by the `Metrics` class. When called, it automatically adds a metric named `ColdStart` with a value of `1` to the metrics buffer. This metric is flushed immediately to ensure it's captured even if other metrics are flushed manually or automatically later. A `ColdStart` metric is only emitted for cold starts; its absence indicates a warm start. ### Usage 1. Import `Metrics` and `MetricUnit` from `@aws-lambda-powertools/metrics`. 2. Initialize the `Metrics` class. 3. Call `metrics.captureColdStartMetric()` within your handler. ### Code Example ```typescript import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders', }); export const handler = async (event: { requestId: string }) => { metrics.captureColdStartMetric(); }; ``` ``` -------------------------------- ### Emit a Single Metric Immediately Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/interfaces/_aws-lambda-powertools_metrics.types.MetricsInterface.html This example demonstrates using the `singleMetric()` method to create a Metrics instance that emits a single metric immediately, bypassing the default buffering. This is useful for metrics that require unique dimensions or immediate flushing, such as cold start metrics. ```typescript import { Metrics } from '@aws-lambda-powertools/metrics'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); export const handler = async () => { const singleMetric = metrics.singleMetric(); // The single metric will be emitted immediately singleMetric.addMetric('coldStart', MetricUnit.Count, 1); // These other metrics will be buffered and emitted when calling `publishStoredMetrics()` metrics.addMetric('successfulBooking', MetricUnit.Count, 1); metrics.publishStoredMetrics(); } ``` -------------------------------- ### Returning Custom Response Objects Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/event-handler/http Use the Web API's Response object to gain full control over the response, such as adding custom headers, cookies, or setting a specific content type. This example demonstrates returning a JSON response with custom headers for a GET request. ```typescript import { Router } from '@aws-lambda-powertools/event-handler/http'; import { Logger } from '@aws-lambda-powertools/logger'; import type { Context } from 'aws-lambda'; const logger = new Logger(); const app = new Router({ logger }); app.get('/todos', async () => { const todos = await getAllTodos(); return new Response(JSON.stringify({ todos }), { status: 200, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=300', 'X-Custom-Header': 'custom-value', }, }); }); app.post('/todos', async ({ req }) => { const body = await req.json(); const todo = await createTodo(body.title); return new Response(JSON.stringify(todo), { status: 201, headers: { Location: `/todos/${todo.id}`, 'Content-Type': 'application/json', }, }); }); export const handler = async (event: unknown, context: Context) => app.resolve(event, context); ``` -------------------------------- ### Install Batch Processing Utility Source: https://docs.aws.amazon.com/powertools/typescript/latest/features/batch Install the AWS Lambda Powertools Batch Processing utility using npm. ```bash npm i @aws-lambda-powertools/batch ``` -------------------------------- ### Manual Lambda Handler Instrumentation with Tracer Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_tracer.index.Tracer.html Manually instrument your Lambda handler using Tracer class methods for fine-grained control. This example demonstrates creating subsegments, adding annotations and metadata for cold starts, service names, responses, and errors, and managing segment lifecycles. ```typescript import { Tracer } from '@aws-lambda-powertools/tracer'; const tracer = new Tracer({ serviceName: 'serverlessAirline' }); export const handler = async (_event: unknown, _context: unknown) => { const segment = tracer.getSegment(); // This is the facade segment (the one that is created by AWS Lambda) // Create subsegment for the function & set it as active const subsegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); tracer.setSegment(subsegment); // Annotate the subsegment with the cold start & serviceName tracer.annotateColdStart(); tracer.addServiceNameAnnotation(); let res; try { // ... your own logic goes here // Add the response as metadata tracer.addResponseAsMetadata(res, process.env._HANDLER); } catch (err) { // Add the error as metadata tracer.addErrorAsMetadata(err as Error); throw err; } finally { // Close the subsegment subsegment.close(); // Set the facade segment as active again tracer.setSegment(segment); } return res; } ``` -------------------------------- ### Install @aws-lambda-powertools/parameters and AWS SDK for SSM Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_parameters.html Install the necessary packages for using the SSM Parameter Store utility. This includes the Powertools parameters library and the AWS SDK v3 client for SSM. ```bash npm install @aws-lambda-powertools/parameters @aws-sdk/client-ssm Copy ``` -------------------------------- ### Install @aws-lambda-powertools/validation Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_validation.html Install the validation package using npm. ```bash npm i @aws-lambda-powertools/validation Copy ``` -------------------------------- ### Metrics Class Initialization and Usage Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_metrics.index.Metrics.html Demonstrates how to initialize the Metrics class with options like namespace, serviceName, and defaultDimensions, and how to add metadata and metrics, followed by publishing them. ```APIDOC ## Class Metrics The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF). ### Constructor * `new Metrics(options?: MetricsOptions): Metrics` * Parameters: * `options`: `MetricsOptions` = {} * Returns: `Metrics` ### Properties * `coldStart`: `boolean` (Protected) * `defaultServiceName`: `string` (Protected, Readonly) ### Methods * `addDimension(dimension: string, value: string): Metrics` * `addDimensions(dimensions: { [key: string]: any }): Metrics` * `addMetadata(key: string, value: any): Metrics` * `addMetric(metricName: string, unit: MetricUnit, value: number): Metrics` * `captureColdStartMetric(value: boolean): Metrics` * `clearDefaultDimensions(): Metrics` * `clearDimensions(): Metrics` * `clearMetadata(): Metrics` * `clearMetrics(): Metrics` * `getColdStart(): boolean` * `getInitializationType(): string` * `hasStoredMetrics(): boolean` * `isDisabled(): boolean` * `isValidServiceName(serviceName: string): boolean` * `logMetrics(options: LogMetricsMetadata): LambdaInterfaceDecorator` * `publishStoredMetrics(): Promise` * `serializeMetrics(): string` * `setDefaultDimensions(dimensions: { [key: string]: any }): Metrics` * `setFunctionName(functionName: string): Metrics` * `setFunctionNameForColdStartMetric(functionName: string): Metrics` * `setThrowOnEmptyMetrics(value: boolean): Metrics` * `setTimestamp(timestamp: Date): Metrics` * `singleMetric(metricName: string, unit: MetricUnit, value: number): Metrics` * `throwOnEmptyMetrics(value: boolean): Metrics` #### Example ```typescript import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics'; const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders', defaultDimensions: { environment: 'dev' }, }); export const handler = async (event: { requestId: string }) => { metrics .addMetadata('request_id', event.requestId) .addMetric('successfulBooking', MetricUnit.Count, 1) .publishStoredMetrics(); }; ``` ``` -------------------------------- ### Install Parameters with Secrets Manager Source: https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/installation Install the Parameters utility and its required AWS SDK client for Secrets Manager. ```bash npm i @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager ``` -------------------------------- ### Service Identifier Example Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/types/_aws-lambda-powertools_logger.index._internal_.PowertoolsStandardKeys.html Example of a unique service identifier. ```typescript "serverlessAirline" ``` -------------------------------- ### Log Message Example Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/types/_aws-lambda-powertools_logger.index._internal_.PowertoolsStandardKeys.html Example of a descriptive log message. ```typescript "Query performed to DynamoDB" ``` -------------------------------- ### Log Level Example Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/types/_aws-lambda-powertools_logger.index._internal_.PowertoolsStandardKeys.html Example of a log level string. ```typescript "INFO" ``` -------------------------------- ### SqsFifoPartialProcessor Constructor Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/classes/_aws-lambda-powertools_batch.index.SqsFifoPartialProcessor.html Initializes a new instance of the SqsFifoPartialProcessor class. ```APIDOC ## new SqsFifoPartialProcessor() ### Description Initializes a new instance of the SqsFifoPartialProcessor class. ### Returns SqsFifoPartialProcessor ``` -------------------------------- ### ConstructorOptions Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_logger.types.html Configuration options for initializing the logger. ```APIDOC ## Type Alias: ConstructorOptions ### Description Defines the structure for options that can be passed when creating a new logger instance. ### Type Definition ```typescript { serviceName?: string; logLevel?: LogLevel; contextEnricher?: (context: any) => Record; jsonReplacer?: CustomJsonReplacerFn; formatters?: { json?: (item: LogItem) => string; text?: (item: LogItem) => string; }; serviceVersion?: string; awsRegion?: string; } ``` ``` -------------------------------- ### Example Log Output with Persistent Keys Source: https://docs.aws.amazon.com/powertools/typescript/latest/llms-full.txt This is an example of the log output when persistent keys are configured. Notice how 'environment' and 'version' are included in the JSON log. ```json { "level": "INFO", "message": "processing transaction", "service": "serverlessAirline", "timestamp": "2021-12-12T21:49:58.084Z", "xray_trace_id": "abcdef123456abcdef123456abcdef123456", "environment": "prod", "version": "1.2.0", } ``` -------------------------------- ### Install Logger Package Source: https://docs.aws.amazon.com/powertools/typescript/latest/api/modules/_aws-lambda-powertools_logger.html Install the @aws-lambda-powertools/logger package using npm. ```bash npm i @aws-lambda-powertools/logger ```