Updated Nov 19, 202610 min read

How to Use AWS SQS with Node.js in 2026: Send, Receive and Dead-Letter Queues

Add a queue to a Node.js or Express app on AWS: the AWS SDK v3 calls, a consumer that deletes only after success, dead-letter queues, and the same setup declared in TypeScript with Encore.

Illustration for How to Use AWS SQS with Node.js in 2026: Send, Receive and Dead-Letter Queues

To add a queue to a Node.js or Express app on AWS, either call Amazon SQS directly with @aws-sdk/client-sqs (send with SendMessageCommand, long-poll with ReceiveMessageCommand, delete after success, and attach a dead-letter queue), or declare a topic and subscription in TypeScript with Encore, which provisions SNS and SQS with dead-letter queues in your own AWS account and runs the handler for you. The SDK route gives you full control of the queue and leaves provisioning, IAM and the consumer process to you. The Encore route removes those, and the same code runs locally under encore run.

Amazon SQS is the default queue on AWS for moving slow work out of a request, such as sending email or processing uploads. The SDK calls are short, and most of the effort goes into long polling, the visibility timeout, deleting only after success, dead-letter queues and IAM policies.

Which way should you add a queue to a Node.js app on AWS?

RankApproachWhat you writeWho runs the consumerLocal developmentBest for
1Encore Pub/Subnew Topic and new Subscription in TypeScriptEncore, inside your serviceIn-memory implementation under encore runTypeScript backends where queues should ship with the feature
2AWS SDK v3 + your own loopSendMessageCommand, ReceiveMessageCommand, DeleteMessageCommandA long-running process you deploy and restartLocalStack or a real dev queueFull control over every SQS setting
3sqs-consumerA handleMessage callbackA long-running process you deploySame as the SDK routeExisting Express or worker apps that want a tested polling loop
4Lambda event source mappingA Lambda handlerAWS LambdaSAM CLI or unit testsShort jobs that fit Lambda's limits

Package versions looked up on November 19, 2026: @aws-sdk/client-sqs 3.1172.0, sqs-consumer 15.0.5 and encore.dev 1.58.9.

ConceptWhat to know
Max message size1 MiB
Long pollingWaitTimeSeconds: 20 on receive
Batch sizeUp to 10 messages per send, receive or delete
Retry mechanismVisibility timeout (30 seconds by default); undeleted messages reappear
Poison messagesDead-letter queue with maxReceiveCount
OrderingStandard queues are best-effort; FIFO queues order per message group

How do you send a message to SQS from Node.js?

Install the SQS client from the AWS SDK for JavaScript v3, which ships each service as its own package:

~/app
$ npm install @aws-sdk/client-sqs
// producer.ts import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"; const sqs = new SQSClient({ region: process.env.AWS_REGION }); const QueueUrl = process.env.ORDERS_QUEUE_URL!; export async function enqueueOrder(orderId: string) { await sqs.send( new SendMessageCommand({ QueueUrl, MessageBody: JSON.stringify({ orderId }), }), ); }

From an Express route, authenticate the caller, validate the body, and write the order and an outbox row in one transaction. A continuously running worker publishes unpublished outbox rows to SQS, so a failed enqueue is retried even when no later order request arrives:

// server.ts import express from "express"; import { enqueueOrder } from "./producer"; import { createOrderWithOutbox, claimPendingOutbox, markOutboxPublished } from "./orders"; const app = express(); app.use(express.json()); app.post("/orders", async (req, res) => { const token = process.env.ORDERS_API_TOKEN; const authorization = req.get("authorization") ?? ""; if (!token || authorization !== `Bearer ${token}`) { res.status(401).json({ error: "unauthenticated" }); return; } const totalCents = req.body?.totalCents; const idempotencyKey = req.get("idempotency-key"); if (!Number.isInteger(totalCents) || totalCents < 0) { res.status(400).json({ error: "totalCents must be a non-negative integer" }); return; } if (typeof idempotencyKey !== "string" || idempotencyKey.length === 0) { res.status(400).json({ error: "Idempotency-Key is required" }); return; } const order = await createOrderWithOutbox({ totalCents, idempotencyKey }); // Optional fast path; the worker below is what retries when traffic is idle. try { await publishPendingOutbox(); } catch (err) { console.error("outbox publish will be retried", err); } res.status(202).json({ orderId: order.id }); }); async function publishPendingOutbox() { for (const row of await claimPendingOutbox()) { await enqueueOrder(String(row.orderId)); await markOutboxPublished(row.id); } } async function runOutboxWorker() { for (;;) { try { await publishPendingOutbox(); } catch (err) { console.error("outbox publish will be retried", err); } await new Promise((resolve) => setTimeout(resolve, 30_000)); } } void runOutboxWorker(); app.listen(Number(process.env.PORT ?? 3000));
// orders.ts import { pool } from "./db"; export async function createOrderWithOutbox(input: { totalCents: number; idempotencyKey: string; }) { const client = await pool.connect(); try { await client.query("BEGIN"); const { rows } = await client.query<{ id: number; inserted: boolean }>( `INSERT INTO orders (total_cents, idempotency_key) VALUES ($1, $2) ON CONFLICT (idempotency_key) DO UPDATE SET total_cents = orders.total_cents RETURNING id, (xmax = 0) AS inserted`, [input.totalCents, input.idempotencyKey], ); if (rows[0].inserted) { await client.query("INSERT INTO order_outbox (order_id) VALUES ($1)", [rows[0].id]); } await client.query("COMMIT"); return rows[0]; } catch (err) { await client.query("ROLLBACK"); throw err; } finally { client.release(); } } export async function claimPendingOutbox() { const { rows } = await pool.query<{ id: number; orderId: string }>( `UPDATE order_outbox SET claimed_at = NOW() WHERE id IN ( SELECT id FROM order_outbox WHERE published_at IS NULL AND (claimed_at IS NULL OR claimed_at < NOW() - INTERVAL '1 minute') ORDER BY id FOR UPDATE SKIP LOCKED ) RETURNING id, order_id AS "orderId"`, ); return rows; } export async function markOutboxPublished(id: number) { await pool.query("UPDATE order_outbox SET published_at = NOW() WHERE id = $1", [id]); }
CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, total_cents INTEGER NOT NULL CHECK (total_cents >= 0), idempotency_key TEXT NOT NULL UNIQUE ); CREATE TABLE order_outbox ( id BIGSERIAL PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders (id), claimed_at TIMESTAMPTZ, published_at TIMESTAMPTZ );

The client resolves credentials through the default provider chain, which means environment variables or a shared profile locally and the IAM role attached to the Lambda function, ECS task or EC2 instance on AWS. SendMessageBatchCommand sends up to 10 messages per call.

How do you receive and delete SQS messages?

A consumer is a loop that long-polls the queue, processes each message and deletes it once the work succeeded:

// consumer.ts import { SQSClient, ReceiveMessageCommand, DeleteMessageCommand, } from "@aws-sdk/client-sqs"; const sqs = new SQSClient({ region: process.env.AWS_REGION }); const QueueUrl = process.env.ORDERS_QUEUE_URL!; async function handle(body: { orderId: string }) { console.log("processing order", body.orderId); } export async function poll() { while (true) { const { Messages = [] } = await sqs.send( new ReceiveMessageCommand({ QueueUrl, MaxNumberOfMessages: 10, WaitTimeSeconds: 20, }), ); for (const m of Messages) { try { await handle(JSON.parse(m.Body!)); await sqs.send( new DeleteMessageCommand({ QueueUrl, ReceiptHandle: m.ReceiptHandle! }), ); } catch (err) { // Not deleted: the message becomes visible again after the timeout. console.error("failed", m.MessageId, err); } } } }

WaitTimeSeconds: 20 turns on long polling, so the call waits for messages instead of returning empty at once, which cuts empty responses and request count. A received message is hidden from other consumers for the queue's visibility timeout, and if the handler runs longer than that, the message reappears and a second consumer processes it in parallel. Set the timeout above your slowest expected handler, or extend it for long jobs with ChangeMessageVisibilityCommand.

Standard queues deliver at least once and occasionally deliver a message twice, so handlers should be idempotent, for example by recording processed order IDs in the database and skipping repeats.

Should you use sqs-consumer instead of a hand-written loop?

For a long-running worker, sqs-consumer usually saves code, as it long-polls for you, and in version 15 a message is deleted only when handleMessage returns it, while a thrown error leaves it on the queue for retry:

// worker.ts import { Consumer } from "sqs-consumer"; const consumer = Consumer.create({ queueUrl: process.env.ORDERS_QUEUE_URL!, handleMessage: async (message) => { const { orderId } = JSON.parse(message.Body!); console.log("processing order", orderId); return message; // returning the message acknowledges and deletes it }, }); consumer.on("processing_error", (err) => console.error(err.message)); consumer.start();

The consumer also needs sqs:ReceiveMessage, sqs:DeleteMessage, sqs:DeleteMessageBatch, sqs:ChangeMessageVisibility and sqs:ChangeMessageVisibilityBatch on the queue, and a process that keeps it running.

How do dead-letter queues and FIFO queues work?

A message that throws on every attempt keeps coming back until its retention period ends, four days by default. A dead-letter queue catches it after a set number of receives: create a second queue and set a redrive policy on the source queue with deadLetterTargetArn and maxReceiveCount, for example 5. Alarm on the dead-letter queue depth in CloudWatch, and use SQS redrive to move messages back after a fix.

FIFO queues, with names ending in .fifo, preserve order within a MessageGroupId and deduplicate within a five-minute window using MessageDeduplicationId or content-based deduplication. Ordering costs throughput, so use FIFO only where order matters, such as events for a single account.

What does the SDK approach leave to you?

Each queue and dead-letter queue has to exist in every environment, usually through Terraform or CDK, along with an IAM policy for each producer and consumer, the queue URL in each service's configuration, a process that runs the polling loop and restarts it, and a local substitute such as LocalStack. When one event needs to reach several consumers, an SNS topic fans out to one queue per consumer, with subscriptions and queue policies on top.

How do you get SQS-backed queues from TypeScript with Encore?

Encore

Encore brings infrastructure from code, so the queue is declared in the TypeScript that uses it rather than in a separate Terraform module. A Pub/Sub topic and its subscriptions are typed objects, and on AWS Encore provisions them as SNS and SQS with dead-letter queues and runs each subscription's handler inside your service, with no polling loop or queue URLs in your code.

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=ts/empty$ cd shop && mkdir orders
// orders/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("orders");
// orders/orders.ts import { api } from "encore.dev/api"; import { Topic, Subscription } from "encore.dev/pubsub"; interface OrderPlaced { orderId: string; } export const orderPlaced = new Topic<OrderPlaced>("order-placed", { deliveryGuarantee: "at-least-once", }); export const placeOrder = api( { expose: true, method: "POST", path: "/orders" }, async ({ orderId }: { orderId: string }): Promise<{ ok: boolean }> => { await orderPlaced.publish({ orderId }); return { ok: true }; }, ); // Throwing an error makes Encore retry the message. const _ = new Subscription(orderPlaced, "send-confirmation", { handler: async (event) => { console.log("sending confirmation for", event.orderId); }, });

encore run runs the topic with a local implementation, so publishing from the endpoint and receiving in the subscription works without AWS credentials or LocalStack, and the local development dashboard shows the publish and the handler call in its traces. A second consumer is another new Subscription on the same topic. Handlers should still be idempotent, as delivery is at least once on SQS either way.

On deploy, Encore provisions the SNS topic, the SQS queues with dead-letter queues, and an IAM role for the service, as described in the AWS infrastructure docs. The same code deploys to GCP Pub/Sub if you choose GCP, and connecting your AWS account is covered in deploying to your own cloud. For a coding agent, adding a consumer is one Subscription in the service that needs it, which it can run and check locally in the same change.

Best fit: TypeScript teams on AWS who want SQS-backed queues with dead-letter handling and local development, declared next to the code that publishes and consumes them.

Frequently asked questions

How do I send a message to SQS from Node.js?

Install @aws-sdk/client-sqs, create an SQSClient for your region, and send a SendMessageCommand with the QueueUrl and a MessageBody string, usually JSON. The SDK picks up credentials from the environment, a shared profile, or the IAM role of the Lambda function, ECS task or EC2 instance.

How do I consume SQS messages in Node.js?

Run a loop that sends ReceiveMessageCommand with WaitTimeSeconds set to 20 for long polling and MaxNumberOfMessages up to 10, processes each message, and deletes it with DeleteMessageCommand using its ReceiptHandle. A message that is not deleted becomes visible again after the visibility timeout and is retried. The sqs-consumer package wraps the same loop.

What is a dead-letter queue in SQS?

A second queue that receives messages which failed processing too many times. You attach it to the source queue with a redrive policy and a maxReceiveCount, so a message that keeps failing moves aside instead of being retried until its retention period runs out.

Can I add an SQS queue to Express without managing SQS by hand?

Yes. With Encore you declare a Topic and a Subscription from encore.dev/pubsub in TypeScript; encore run gives you a local implementation, and on AWS Encore provisions SNS and SQS with a dead-letter queue and runs the subscription handler for each message, so there is no queue URL, polling loop or IAM policy in your code.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders