Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Consumer
✓ import { Consumer } from 'sqs-consumer';
✗ import Consumer from 'sqs-consumer';
const Consumer = require('sqs-consumer');
The primary entry point is a named export `Consumer`, which is a factory function. CommonJS `require()` is not supported in recent major versions.
SQSClient
✓ import { SQSClient } from '@aws-sdk/client-sqs';
✗ import { SQS } from 'aws-sdk';
The library expects an instance of `SQSClient` from AWS SDK v3, not the older `aws-sdk` package (v2).
ConsumerOptions
✓ import { ConsumerOptions } from 'sqs-consumer';
Type definition for configuring the SQS consumer, useful for TypeScript projects.
Message
✓ import { Message } from '@aws-sdk/client-sqs';
The type definition for an SQS message, useful for typing the `handleMessage` callback.
This quickstart demonstrates how to create and start an SQS consumer using `sqs-consumer`, process messages asynchronously, handle errors during message processing, and implement graceful shutdown. It uses `SQSClient` from AWS SDK v3 and includes relevant event listeners.
import { Consumer } from 'sqs-consumer';
import { SQSClient, Message } from '@aws-sdk/client-sqs';
// Ensure environment variables are set for AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
// or pass credentials directly to SQSClient configuration.
const REGION = process.env.AWS_REGION ?? 'us-east-1';
const SQS_QUEUE_URL = process.env.SQS_QUEUE_URL ?? 'https://sqs.us-east-1.amazonaws.com/123456789012/my-test-queue';
if (!process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY) {
console.warn('AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) are not set in environment variables. Consumer may fail without proper authentication.');
}
const sqs = new SQSClient({ region: REGION });
const app = Consumer.create({
queueUrl: SQS_QUEUE_URL,
handleMessage: async (message: Message) => {
// This function is called for each message received.
console.log(`Processing message: ${message.MessageId}`);
console.log(`Message Body: ${message.Body}`);
try {
const data = JSON.parse(message.Body ?? '{}');
console.log('Parsed data:', data);
// Simulate some asynchronous work.
await new Promise(resolve => setTimeout(resolve, Math.random() * 500));
console.log(`Successfully processed and acknowledged message ${message.MessageId}`);
// Returning nothing (or a fulfilled promise) implies successful processing and message deletion.
} catch (error) {
console.error(`Error processing message ${message.MessageId}:`, error);
// If handleMessage throws, the message will NOT be deleted and will return to the queue for retry.
throw error; // Re-throw to signal a processing failure.
}
},
sqs: sqs, // Pass the instantiated SQSClient
batchSize: 5, // Process up to 5 messages at once
visibilityTimeout: 30, // seconds
terminateVisibilityTimeout: true // Ensures messages are retried faster on processing_error
});
app.on('error', (err) => {
console.error('Consumer-level error (e.g., SQS polling issue):', err.message);
});
app.on('processing_error', (err, message) => {
console.error(`Handler error for message ${message.MessageId}:`, err.message);
// This event is fired when handleMessage throws an error.
// The message will not be deleted and will be retried (potentially immediately if terminateVisibilityTimeout is true).
});
app.on('timeout_exceeded', (message) => {
console.warn(`Message processing timed out for ${message.MessageId}.`);
});
app.on('empty', () => {
console.log('Queue is currently empty. Waiting for new messages...');
});
app.start();
console.log('SQS Consumer started. Waiting for messages...');
// Graceful shutdown on application exit signals
process.on('SIGTERM', async () => {
console.log('SIGTERM received. Stopping consumer...');
await app.stop();
console.log('Consumer stopped. Exiting.');
process.exit(0);
});
process.on('SIGINT', async () => {
console.log('SIGINT received. Stopping consumer...');
await app.stop();
console.log('Consumer stopped. Exiting.');
process.exit(0);
});
Debug
Known issues
breaking`sqs-consumer` transitioned to an ES Module (ESM) codebase and expects usage with `import` statements. Attempting to use CommonJS `require()` will result in import errors or `TypeError`s. This change typically aligns with versions that integrate AWS SDK v3.fixMigrate your import statements from `const { Consumer } = require('sqs-consumer');` to `import { Consumer } from 'sqs-consumer';`. affects: >=13.0.0
gotchaErrors thrown within the `handleMessage` function are critical. If an `async handleMessage` function throws an error (or returns a rejected promise), the message will NOT be automatically deleted from the SQS queue. It will become visible again after its visibility timeout expires, potentially leading to infinite retries if not handled by a dead-letter queue (DLQ) policy. Ensure your `handleMessage` logic is robust or uses `terminateVisibilityTimeout`.fixImplement comprehensive `try...catch` blocks within `handleMessage` to explicitly manage errors. Consider setting `terminateVisibilityTimeout: true` in consumer options to make failed messages available sooner for retry. Always configure a Dead Letter Queue (DLQ) for your SQS queue to prevent poison messages from indefinitely re-appearing.
affects: >=1.0.0
gotchaIncorrect AWS Identity and Access Management (IAM) permissions for the SQS queue will prevent the consumer from polling or deleting messages. Required permissions include `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:DeleteMessageBatch`, `sqs:ChangeMessageVisibility`, `sqs:ChangeMessageVisibilityBatch`, `sqs:GetQueueAttributes`, and `sqs:GetQueueUrl`.fixVerify that the IAM role or user associated with your application has the necessary SQS permissions attached. Use `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_REGION` environment variables or pass a pre-configured `SQSClient` instance with correct credentials and region.
affects: >=1.0.0
gotchaPrior to version `14.2.7-canary.2`, a bug existed where unhandled errors within `handleMessage` could cause the entire consumer polling loop to crash, effectively stopping message processing entirely. While fixed in newer versions, it highlights the importance of robust error handling.fixUpgrade to `sqs-consumer@14.2.7` or later. Always wrap your `handleMessage` logic in a `try...catch` block to prevent exceptions from propagating and impacting the consumer's stability.
affects: <14.2.7-canary.2
Errors
Common errors & fixes
Error: Missing credentials in config
The AWS SDK (used by sqs-consumer) cannot find AWS credentials in the environment, shared credential file, or passed SQSClient configuration.
fixEnsure `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables are set, or provide an `SQSClient` instance with credentials explicitly defined in the `Consumer.create` options.
TypeError: (0 , sqs_consumer_1.Consumer) is not a function
Attempting to import `Consumer` using a default import syntax (`import Consumer from 'sqs-consumer'`) or CommonJS `require()` when the package is an ES Module with named exports.
fixChange your import statement to `import { Consumer } from 'sqs-consumer';` for ES Modules. AccessDeniedException: User: arn:aws:iam::ACCOUNT_ID:user/IAM_USER is not authorized to perform: sqs:ReceiveMessage on resource: QUEUE_URL
The AWS IAM principal (user or role) configured for the application lacks the necessary permissions to interact with the specified SQS queue.
fixReview and update the IAM policy attached to your AWS user or role, ensuring it includes required permissions like `sqs:ReceiveMessage`, `sqs:DeleteMessage`, and `sqs:ChangeMessageVisibility` for the target queue.
Consumer-level error (e.g., SQS polling issue): AWS.SimpleQueueService.QueueDoesNotExist: The specified queue does not exist for this wsdl version.
The `queueUrl` provided to `Consumer.create` is incorrect, or the queue does not exist in the specified AWS region.
fixDouble-check the `queueUrl` and `region` provided in the `Consumer.create` options. Ensure the SQS queue exists and its URL matches the configured value.
Audit
Dependencies
@aws-sdk/client-sqsrequiredRequired for interacting with the Amazon SQS service. The library is built on AWS SDK v3.