Search code examples
node.jsaws-sdkamazon-sqsaws-sdk-nodejs

Getting error while using @aws-sdk/client-sqs in node.js


While using the sendMessage method of SQS getting the following error error SyntaxError: Unexpected token T in JSON at position 0 Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object. at JSON.parse (<anonymous>) at /var/www/html/apachedev/git/repo/node_modules/@aws-sdk/client-sqs/dist-cjs/protocols/Aws_json1_0.js:1981:21

Error is coming from the following part of Aws_json1_0.js Here the encoded variable is having this value There was an internal server error.

const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
    if (encoded.length) {
        console.log(encoded);
        return JSON.parse(encoded);
    }
    return {};
});

Code snippet:

import { SQS } from "@aws-sdk/client-sqs";
async enqueueMessage(message: NewMessage): Promise<QueuedMessage> {    
    console.log(message, MESSAGE_QUEUE_URL);
    const result = await this.sqsClient
      .sendMessage({
        QueueUrl: MESSAGE_QUEUE_URL,
        MessageBody: JSON.stringify(message),
      });
    console.log("RESULT", result);
    return {
      id: result.MessageId || '',
      ...message,
    };
  }

In the above snippet the message and the queue url looks correct.

value of message:

{
  user_id: '68057407',
  queued_by: 'abc@gmail.com',
  action: 'download',
  filters: {},
  report_id: 10,
  title: 'Title',
  download_id: 3722
}

value of MESSAGE_QUEUE_URL: http://localhost:9324/queue/jobQueue

versions: "@aws-sdk/client-sqs": "^3.431.0" Node.js: v18.18.1

Tried to use the sendMessage method, but it didn't add the message to the queue.


Solution

  • Are you using Localstack? I saw the MESSAGE_QUEUE_URL to be pointing to http://localhost:9324. If yes, you may need to pull the latest image from yesterday (11/23/23)

    There was a recent change in the AWS SDK wherein the AWS JSON protocol is used by default. However, Localstack expects the AWS query protocol format.

    https://github.com/localstack/localstack/issues/8267#issuecomment-1803663216