# @fgiova/fastify-sqs-consumer

> sqs-consumer fastify plugin

Latest version **3.5.0** (published 2026-11-06) · MIT license · 0 weekly downloads

## Install

```sh
npm install @fgiova/fastify-sqs-consumer
pnpm add @fgiova/fastify-sqs-consumer
yarn add @fgiova/fastify-sqs-consumer
bun add @fgiova/fastify-sqs-consumer
```

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 3.5.0 |
| Published | 2026-11-06 |
| First published | 2023-08-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | ^22.14.0 \|\| >= 24.10.0 |
| Dependencies | 3 |
| Unpacked size | 32.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 5 |
| Author | Francesco Giovannini |
| Maintainers | fgiova_user |
| Keywords | fastify, sqs, sqs-consumer, consumer, aws, amazon |

## Links

- npm: https://www.npmjs.com/package/@fgiova/fastify-sqs-consumer
- Repository: https://github.com/fgiova/fastify-sqs-consumer
- Homepage: https://github.com/fgiova/fastify-sqs-consumer#readme
- Issues: https://github.com/fgiova/fastify-sqs-consumer/issues
- npm.io page: https://npm.io/package/@fgiova/fastify-sqs-consumer

## Dependencies (3)

- [fastify-plugin](https://npm.io/package/fastify-plugin.md) ^5.1.0
- [@fgiova/sqs-consumer](https://npm.io/package/@fgiova/sqs-consumer.md) ^3.5.0
- [@watchable/unpromise](https://npm.io/package/@watchable/unpromise.md) ^1.0.2

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 3.5.0 (latest) — 2026-11-06
- 3.4.0 — 2026-11-05
- 3.3.0 — 2026-10-23
- 3.2.0 — 2026-10-08
- 3.1.1 — 2026-09-28
- 3.1.0 — 2026-06-08
- 3.0.1 — 2026-05-08
- 3.0.0 — 2026-02-13
- 2.0.1 — 2025-09-03
- 2.0.0 — 2025-09-03
- 1.1.0 — 2023-09-05
- 1.0.0 — 2023-08-25

## README

# fastify sqs-consumer
[![NPM version](https://img.shields.io/npm/v/@fgiova/fastify-sqs-consumer.svg?style=flat)](https://www.npmjs.com/package/@fgiova/fastify-sqs-consumer)
![CI workflow](https://github.com/fgiova/fastify-sqs-consumer/actions/workflows/node.js.yml/badge.svg)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
[![Linted with Biome](https://img.shields.io/badge/Linted_with-Biome-60a5fa?style=flat&logo=biome)](https://biomejs.dev)
[![Maintainability](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer/maintainability.svg)](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer)
[![Code Coverage](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer/coverage.svg)](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer)

## Description
This plugin for fastify 5.x (for fastify 4.x use 1.x ver) allows you to consume messages from AWS SQS queues.
On fastify shutdown a simple wait function is called to wait for the end of the processing of the messages in progress.

**Warning**<br>
To use this plugin, you must have correctly configured your [AWS credentials](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html).<br>
This plugin uses [@fgiova/mini-sqs-client](https://www.npmjs.com/package/@fgiova/mini-sqs-client) and [@fgiova/sqs-consumer](https://www.npmjs.com/package/@fgiova/sqs-consumer) to interact with SQS service.

## Install
```bash
npm i @fgiova/fastify-sqs-consumer
```

## Usage

### ESM
```js
import fastify from "fastify";
import sqsConsumer from "@fgiova/fastify-sqs-consumer";

const app = fastify();

app.register(sqsConsumer, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        waitTimeSeconds: 20,
        timeout: 10_000,
        batchSize: 10,
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);
```

### CommonJS
```js
const fastify = require("fastify")();

fastify.register(require("@fgiova/fastify-sqs-consumer").default, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        waitTimeSeconds: 20,
        timeout: 10_000,
        batchSize: 10,
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);
```

## Options
Options are an array of objects with the following properties (one for each queue):

| Option                | Type                                | Description                                                                                                                                                                                                                                                                                                           |
|-----------------------|-------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| arn*                  | string                              | The ARN of the Amazon SQS queue from which messages are received.                                                                                                                                                                                                                                                     |
| handlerFunction*      | function                            | The function that will be called for each message.                                                                                                                                                                                                                                                                    |
| name                  | string                              | An optional name for the consumer (useful for add [hooks](https://github.com/fgiova/sqs-consumer?tab=readme-ov-file#hooks) post config). If not provided, uuid is assigned.                                                                                                                                           |
| waitTimeSeconds       | number                              | The duration (in seconds, default 20s) for which the call waits for a message to arrive in the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages. |
| timeout               | number                              | The duration before the message is considered as failed: default 90000ms.                                                                                                                                                                                                                                             |
| batchSize             | number                              | The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be returned). Valid values: 1 to 10. Default: 1.                                                                                                                                      |
| attributeNames        | string[]                            | Array of message system attributes to retrieve for each message.                                                                                                                                                                                                                                                      |
| messageAttributeNames | string[]                            | Array of custom message attributes to retrieve for each message.                                                                                                                                                                                                                                                      |
| parallelExecution     | boolean                             | Enable parallel execution of message handlers.                                                                                                                                                                                                                                                                        |
| credentials           | {accessKeyId, secretAccessKey}      | Explicit AWS credentials (alternative to environment configuration).                                                                                                                                                                                                                                                  |
| backoff               | number \| (attempt: number, message: Message) => number | Delay (in seconds, 0-43200) before a failed message becomes visible again. A number sets a fixed delay; a function receives the attempt number (`ApproximateReceiveCount`, requested automatically) and the message, and returns the delay. Default: 0 (immediate retry).                                                                |
| maxRetries            | number \| (attempt: number, message: Message) => number | Maximum receive count before giving up on a failed message. When `ApproximateReceiveCount` (requested automatically) reaches this value, the `onMaxReceiveCountExceeded` event is fired and the message is deleted unless the event returns `false` (also when no event is registered). A function receives the attempt number and the message, and returns the limit. Default: unlimited. |
| events                | object                              | Events functions for the consumer (detail in next table).                                                                                                                                                                                                                                                             |
| sqs                   | MiniSQSClient \| SQSOptions          | Either an initialized [@fgiova/mini-sqs-client](https://www.npmjs.com/package/@fgiova/mini-sqs-client) instance (useful for testing sessions) or an options object used to build the client (see below).                                                                                                              |

\* required

### sqs options object

Instead of passing a pre-built `MiniSQSClient`, you can pass an options object so the plugin builds the client for you:

| Option        | Type                            | Description                                                                                  |
|---------------|---------------------------------|----------------------------------------------------------------------------------------------|
| endpoint      | string                          | Custom SQS endpoint (e.g. a local LocalStack/ElasticMQ instance).                            |
| undiciOptions | Pool.Options                    | [undici](https://undici.nodejs.org/#/docs/api/Pool) `Pool` options for the underlying HTTP client. |
| credentials   | {accessKeyId, secretAccessKey}  | Explicit AWS credentials. The top-level `credentials` option takes precedence over this one. |

```js
app.register(sqsConsumer, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        sqs: {
            endpoint: "http://localhost:4566",
            undiciOptions: { connections: 1 },
            credentials: {
                accessKeyId: "AWS_ACCESS_KEY_ID",
                secretAccessKey: "AWS_SECRET_ACCESS_KEY"
            }
        },
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);
```

## Decorators

### sqsConsumers

`sqsConsumers` is a `Record<string, { consumer: SQSConsumer, meta: { pendingMessages: number }, ownedClient?: MiniSQSClient }>` that provides access to the registered consumers and their metadata, keyed by consumer name.
It is a null-prototype object (`Object.create(null)`): use `Object.hasOwn(app.sqsConsumers, name)` or `name in app.sqsConsumers` instead of `app.sqsConsumers.hasOwnProperty(name)`.

The consumer lifecycle (start/stop) is managed by the plugin: do not call `start()` or `stop()` on these instances directly.

### addSQSConsumer

`addSQSConsumer(options: ConsumerOptions): string | null` adds a consumer at runtime. `options` accepts the same object used for each entry of the plugin options array (see [Options](#options)); the `ConsumerOptions` type is exported by the package.

- Returns the consumer name (the generated uuid when `name` is not provided), or `null` if the consumer was not created.
- Before the server is ready, the consumer is started together with the others in the `onReady` hook; after that, it is started immediately.
- Returns `null` (and logs a warning) when a consumer with the same name already exists or when the server is closing.

```js
import fastify from "fastify";
import sqsConsumer from "@fgiova/fastify-sqs-consumer";

const app = fastify();
await app.register(sqsConsumer, []);
await app.listen({ port: 3000 });

const name = app.addSQSConsumer({
    arn: "arn:aws:sqs:eu-central-1:000000000000:MyOtherQueue",
    handlerFunction: async (message, fastify) => {
        return true;
    }
});
```

## handlerFunction

Handler function is an async function called for each message received from the queue.
Each Error thrown by the function is caught and the message is not deleted from the queue.
Otherwise, the message is deleted from the queue.

### Events

| Option           | Type                                                                  | Description                                                         |
|------------------|-----------------------------------------------------------------------|---------------------------------------------------------------------|
| onPoll           | (messages: Message[]) => Promise<Message[]>                           | Called when the consumer polls for messages                         |
| onMessage        | (message: Message) => Promise<Message>                                | Called when the consumer receives a message                         |
| onHandle         | (message: Message) => Promise<Message>                                | Called when the consumer handles a message                          |
| onHandlerSuccess | (message: Message) => Promise<Message>                                | Called when the consumer handles a message successfully             |
| onHandlerTimeout | (message: Message) => Promise<Message>                                | Called when the consumer handler execution exceed executionTimeout  |
| onHandlerError   | (message: Message, error: Error) => Promise<Boolean>                  | Called when the consumer handler execution throws an error          |
| onMaxReceiveCountExceeded | (message: Message, count: number) => Promise<Boolean>        | Called when a failed message reaches `maxRetries`; return `false` to keep it (released with the usual backoff) |
| onSuccess        | (message: Message) => Promise<Message>                                | Called when the consumer handler execution finishes successfully    |
| onError          | ( hook: HookName, message: Message, error: Error) => Promise<Boolean> | Called when the consumer handler execution throws an uncaught error |
| onSQSError       | (error: Error, message?: Message) => Promise<void>                    | Called when the consumer receives an error from the SQS service     |

## License
Licensed under [MIT](./LICENSE).

---
_Source: https://npm.io/package/@fgiova/fastify-sqs-consumer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
