The SQS client utilities provide a reusable singleton instance of SQSClient for use in AWS Lambda functions. These utilities enable you to configure the client once and reuse it across invocations, following AWS best practices for Lambda performance optimization.
The utility exports the following functions:
initializeSQSClient()- Initialize the SQS client with optional configurationgetSQSClient()- Get the singleton SQS client instancesendToQueue()- Send a message to an SQS queueresetSQSClient()- Reset the client instance (useful for testing)
import { sendToQueue } from '@leanstacks/lambda-utils';
export const handler = async (event: any) => {
// Send a message to an SQS queue
const messageId = await sendToQueue('https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue', {
orderId: '12345',
status: 'completed',
});
return {
statusCode: 200,
body: JSON.stringify({ messageId }),
};
};Message attributes enable SQS subscribers to filter messages based on metadata:
import { sendToQueue, SQSMessageAttributes } from '@leanstacks/lambda-utils';
export const handler = async (event: any) => {
const attributes: SQSMessageAttributes = {
priority: {
DataType: 'String',
StringValue: 'high',
},
attempts: {
DataType: 'Number',
StringValue: '1',
},
};
const messageId = await sendToQueue(
'https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue',
{ orderId: '12345', status: 'completed' },
attributes,
);
return { statusCode: 200, body: JSON.stringify({ messageId }) };
};SQS supports binary data in message attributes:
import { sendToQueue, SQSMessageAttributes } from '@leanstacks/lambda-utils';
export const handler = async (event: any) => {
const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
const attributes: SQSMessageAttributes = {
imageData: {
DataType: 'Binary',
BinaryValue: binaryData,
},
};
const messageId = await sendToQueue(
'https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue',
{ imageId: '12345' },
attributes,
);
return { statusCode: 200, body: JSON.stringify({ messageId }) };
};For advanced use cases, you can access the underlying SQS client:
import { getSQSClient } from '@leanstacks/lambda-utils';
import { ListQueuesCommand } from '@aws-sdk/client-sqs';
export const handler = async (event: any) => {
const client = getSQSClient();
const response = await client.send(new ListQueuesCommand({}));
return {
statusCode: 200,
body: JSON.stringify(response.QueueUrls),
};
};import { initializeSQSClient } from '@leanstacks/lambda-utils';
// Initialize client with custom configuration (typically done once outside the handler)
initializeSQSClient({
region: 'us-west-2',
endpoint: 'http://localhost:9324', // For local development with LocalStack
});
export const handler = async (event: any) => {
// Client is now initialized and ready to use
// Use sendToQueue or getSQSClient as needed
};import { initializeSQSClient, sendToQueue } from '@leanstacks/lambda-utils';
// Initialize client outside the handler (runs once per cold start)
initializeSQSClient({ region: process.env.AWS_REGION });
export const handler = async (event: any) => {
const messageId = await sendToQueue(process.env.QUEUE_URL!, {
timestamp: new Date().toISOString(),
data: event,
});
return {
statusCode: 200,
body: JSON.stringify({ messageId }),
};
};Initializes the SQS client with the provided configuration.
Parameters:
config(optional) - SQS client configuration object
Returns:
- The
SQSClientinstance
Notes:
- If called multiple times, it will replace the existing client instance
- If no config is provided, uses default AWS SDK configuration
Returns the singleton SQS client instance.
Returns:
- The
SQSClientinstance
Notes:
- If the client has not been initialized, creates one with default configuration
- Automatically initializes the client on first use if not already initialized
Sends a message to an SQS queue.
Parameters:
queueUrl(string) - The URL of the SQS queue to send tomessage(Record<string, unknown>) - The message content (will be converted to JSON string)attributes(optional) - Message attributes for filtering
Returns:
- Promise that resolves to the message ID (string)
Throws:
- Error if the SQS send operation fails
Notes:
- Automatically initializes the SQS client if not already initialized
- Message is automatically serialized to JSON
- Returns empty string if MessageId is not provided in the response
Resets the SQS client instance to null.
Notes:
- Primarily useful for testing scenarios where you need to reinitialize the client with different configurations
- After calling this, the client will be automatically re-initialized on next use
Type definition for SQS message attributes.
Interface:
interface SQSMessageAttributes {
[key: string]: {
DataType: 'String' | 'Number' | 'Binary';
StringValue?: string;
BinaryValue?: Uint8Array;
};
}Supported Data Types:
String- UTF-8 encoded string valuesNumber- Numeric values (stored as strings)Binary- Binary data
Note: Unlike SNS, SQS does not support array data types (String.Array).
-
Initialize Outside the Handler: Always initialize the client outside your Lambda handler function to reuse the instance across invocations.
-
Use Environment Variables: Configure the client using environment variables for flexibility across environments.
-
Error Handling: Always wrap send operations in try-catch blocks to handle errors gracefully.
-
Message Attributes: Use message attributes for message filtering and routing rather than including filter criteria in the message body.
-
Testing: Use
resetSQSClient()in test setup/teardown to ensure clean test isolation.
const attributes: SQSMessageAttributes = {
priority: {
DataType: 'String',
StringValue: 'high',
},
};const attributes: SQSMessageAttributes = {
temperature: {
DataType: 'Number',
StringValue: '72.5',
},
};const attributes: SQSMessageAttributes = {
thumbnail: {
DataType: 'Binary',
BinaryValue: new Uint8Array([1, 2, 3, 4]),
},
};import { initializeSQSClient, sendToQueue, resetSQSClient } from '@leanstacks/lambda-utils';
describe('MyLambdaHandler', () => {
beforeEach(() => {
resetSQSClient();
initializeSQSClient({
region: 'us-east-1',
endpoint: 'http://localhost:9324', // LocalStack
});
});
afterEach(() => {
resetSQSClient();
});
it('should send message to SQS queue', async () => {
const messageId = await sendToQueue('https://sqs.us-east-1.amazonaws.com/123456789012/TestQueue', {
test: 'data',
});
expect(messageId).toBeTruthy();
});
});import { sendToQueue } from '@leanstacks/lambda-utils';
export const handler = async (event: any) => {
try {
const messageId = await sendToQueue(
process.env.QUEUE_URL!,
{ orderId: event.orderId, status: 'processing' },
{
priority: {
DataType: 'String',
StringValue: 'high',
},
},
);
return {
statusCode: 200,
body: JSON.stringify({ success: true, messageId }),
};
} catch (error) {
console.error('Failed to send message to SQS', error);
return {
statusCode: 500,
body: JSON.stringify({ success: false, error: 'Failed to send message' }),
};
}
};