0

I'm working on a Next.js project where I'm using the Email Octopus API to fetch a list of subscribers and send emails to them. I've written a function to fetch the subscribers and another function to send the emails. However, when I run my code, I encounter an error that says Unexpected token '<', "<!DOCTYPE "... is not valid JSON

import { NextApiRequest, NextApiResponse } from "next";
import fetch from "node-fetch";

const API_KEY = process.env.EMAIL_OCTOPUS_API_TOKEN;
const LIST_ID = "7461314a-e0c6-15ed-b27c-1d536dc58d8b";
const FROM_EMAIL = "hello@helpus.com";
const SUBJECT = "Hello";
const EMAIL_OCTOPUS_API_BASE = "https://emailoctopus.com/api/1.6";

const getSubscribers = async () => {
  console.log("Email Octopus API Key:", API_KEY);

  const response = await fetch(
    `${EMAIL_OCTOPUS_API_BASE}/lists/${LIST_ID}/contacts?api_key=${API_KEY}`,
  );

  const text = await response.text(); // Get the response as text

  console.log("API Response:", text); // Log the response text

  try {
    const data = JSON.parse(text); // Try to parse the text as JSON

    if (data.error) {
      throw new Error(data.error.message);
    }

    return data.data;
  } catch (error) {
    console.error("Error parsing JSON:", error);
    throw error;
  }
};

const sendEmail = async (subscriber) => {
  const payload = {
    api_key: API_KEY,
    list_id: LIST_ID,
    to: subscriber.email_address,
    from: FROM_EMAIL,
    subject: SUBJECT,
    content: {
      html: "<p>Hie</p>",
      text: "Hie",
    },
  };

  const response = await fetch(`${EMAIL_OCTOPUS_API_BASE}/campaigns`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });

  const data = await response.json();

  if (data.error) {
    throw new Error(data.error.message);
  }

  console.log(`Email sent to ${subscriber.email_address}`);
};

export default async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    const subscribers = await getSubscribers();

    for (const subscriber of subscribers) {
      await sendEmail(subscriber);
    }

    res.status(200).json({ message: "Emails sent successfully" });
  } catch (error) {
    console.error("Error:", error);
    res.status(500).json({ message: error.message });
  }
};

And here's the error I get:

{
  "data": [
    {
      "id": "a56a3452-e0c6-11ed-ae99-d57a81aa766c",
      "email_address": "example@gmail.com",
      "fields": {
        "FirstName": "user1",
        "LastName": null
      },
      "status": "SUBSCRIBED",
      "created_at": "2023-04-22T04:32:10+00:00",
      "tags": []
    },
    {
      "id": "3acef580-e0c9-11ed-b653-8171a0e03c88",
      "email_address": "contact@gmail.com",
      "fields": {
        "FirstName": "user2",
        "LastName": null
      },
      "status": "SUBSCRIBED",
      "created_at": "2023-04-22T04:50:39+00:00",
      "tags": []
    },
    {
      "id": "9ca52a66-e0c6-11ed-962a-99e83e1b26ef",
      "email_address": "test@gmail.com",
      "fields": {
        "FirstName": "user3",
        "LastName": null
      },
      "status": "SUBSCRIBED",
      "created_at": "2023-04-22T04:31:55+00:00",
      "tags": []
    }
  ],
  "paging": {
    "previous": null,
    "next": null
  }
}

Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"

I was expecting my code to fetch the list of subscribers and send emails to them without any issues. I've checked the API response, and it appears to be valid JSON, so I'm not sure why I'm encountering this error.

I've also tried logging the response text to see if there's anything unusual in it, but I couldn't find anything that would cause this error. I was testing this nextjs api route in Thunder client and as you can see i am stuck here for the past 3 days.

Can anyone help me understand what's going wrong and how to fix this issue? I'd really appreciate any guidance or suggestions. Thanks in advance!

Sanushi Salgado
  • 1,195
  • 1
  • 11
  • 18
  • You're trying to decode XML/HTML as JSON. Use a debugger and put in a breakpoint to see what the actual string is that you're trying to decode. We can't possibly know why this is happening though without you having done the basic debugging. This is not a [mre] so it's not like we can just run the code ourselves and check. – Random Davis May 11 '23 at 18:11

0 Answers0