# TypeScript with RabbitMQ and LavinMQ

We recommend [amqp-client.js](https://github.com/cloudamqp/amqp-client.js). It reconnects automatically, recovers your consumers after a reconnect, ships its own type definitions and has no dependencies. It runs in Node.js, Bun, Deno and the browser.

```bash
npm install @cloudamqp/amqp-client
```

## Publish and consume

These files use Node.js. Set `"type": "module"` in `package.json`, and set `BROKER_URL` to the AMQP URL from your instance’s details page in the CloudAMQP console. Without it, the examples connect to a local broker.

Save the connection helper as `amqp.ts`:

```typescript
import { AMQPSession } from "@cloudamqp/amqp-client"

// The session reconnects automatically and recovers consumers
export function connect(): Promise<AMQPSession> {
  return AMQPSession.connect(process.env.BROKER_URL || "amqp://guest:guest@localhost")
}
```

Save the publisher as `publisher.ts`:

```typescript
import type { AMQPSession } from "@cloudamqp/amqp-client"
import { connect } from "./amqp.ts"

// Resolves once the broker has confirmed the message
export async function publish(session: AMQPSession, queueName: string, message: string) {
  const queue = await session.queue(queueName, { durable: true })
  await queue.publish(message, { deliveryMode: 2 })
  console.log(` [x] Sent '${message}'`)
}

if (import.meta.main) {
  const session = await connect()
  await publish(session, "hello", "Hello world!")
  await session.stop()
}
```

Save the consumer as `worker.ts` in the same directory:

```typescript
import type { AMQPSession } from "@cloudamqp/amqp-client"
import { connect } from "./amqp.ts"

// The message is acked when the callback returns, and requeued if it throws
export async function consume(
  session: AMQPSession,
  queueName: string,
  handler: (message: string) => void | Promise<void>,
) {
  const queue = await session.queue(queueName, { durable: true })
  return queue.subscribe({ prefetch: 10 }, async (msg) => {
    await handler(msg.bodyString() ?? "")
  })
}

if (import.meta.main) {
  const session = await connect()
  await consume(session, "hello", (message) => console.log(` [x] Received '${message}'`))
  console.log(" [*] Waiting for messages. To exit press CTRL+C")
  process.on("SIGINT", async () => {
    await session.stop()
  })
}
```

Node.js 24.2 and later run `.ts` files directly, without a build step. Run `node worker.ts` in one terminal and `node publisher.ts` in another.

A runnable example is in [typescript/amqp-client in cloudamqp/examples](https://github.com/cloudamqp/examples/tree/main/typescript/amqp-client). The same example in plain JavaScript is on the [JavaScript page](/docs/javascript/).

## Good to know

- **Connect with the URL.** `AMQPSession.connect(url)`, where the URL is the one on your instance’s details page in the CloudAMQP console. With `amqps://` the server certificate is verified.
- **Use `AMQPSession`**, the high-level API. It reconnects with exponential backoff and recovers subscriptions; `AMQPClient` is the low-level API that doesn’t.
- **Make handlers idempotent**, because a message can be delivered again after a reconnect.
- **Set a prefetch limit** when you subscribe, so a consumer doesn’t buffer more messages than it can handle.
- **In the browser**, use a `wss://` URL; the client then connects over WebSockets. See [AMQP over WebSockets](/docs/amqp-over-websockets/).

See the [API documentation](https://cloudamqp.github.io/amqp-client.js/) for codecs, RPC and the low-level API.

## Other JavaScript libraries

- [amqplib](https://github.com/amqp-node/amqplib), a widely used Node.js client without automatic reconnection

## Video

Here’s a video showing how to set up a CloudAMQP instance and connect to it from Node.js with amqplib:

https://www.youtube.com/embed/9V8Fbbup-WQ
