1. Node.js
  2. Tutorial

Build Consumer

Next, create the JavaScript consumer application by pasting the following code into a file consumer.js.

const { Kafka } = require('kafkajs')

const kafka = new Kafka({
  // User-specific properties that you must set
  clientId: 'my-app',
  brokers: ['<BOOTSTRAP SERVERS>'],

  // Fixed properties
  ssl: true,
  sasl: {
    mechanism: 'plain',
    username: 'unused',
    password: 'token:<API KEY>',
  },
})

async function receive() {
  let topic = 'purchases'

  const consumer = kafka.consumer({
    groupId: 'kafka-nodejs-getting-started',
  })
  await consumer.connect()
  console.log('Connected to Kafka')

  await consumer.subscribe({ topic: topic, fromBeginning: true })

  await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
      let k = message.key.toString().padEnd(10, ' ')
      let value = message.value.toString()
      console.log(
        `Consumed event from topic ${topic}: key = ${k} value = ${value}`
      )
    },
  })
}

receive().catch((err) => {
  console.error(`Something went wrong:\n${err}`)
  process.exit(1)
})

Fill in the appropriate <BOOTSTRAP SERVERS> endpoint and <API KEY> in the brokers and sasl.password properties where the client configuration object is created.

Previous
Build Producer