Use Telegram To Get Notified About Critical Errors

What was the initial problem?

Lately, I had a bug in which user creation failed, and I didn't notice it for days until I was curious why no new users had signed up. It turned out I had introduced a bug in the code, but I didn't notice it for days. I therefore searched for an easy way to get notified about critical errors.

Why I use Telegram

My philosophy is KISS (Keep It Simple, Stupid). I don't want to have a complex setup and want to be notified directly on my phone; I do not need any third-party service. I want to have a simple setup that is free and works. If I need more, I can always switch to more advanced solutions that are not free.

How to setup Telegram

  1. Create a file libs/telegram.ts (or wherever you want to put it)
  2. Add the following code:
// Retrieve the bot token and chat ID from environment variables
const botToken = process.env.TELEGRAM_BOT_TOKEN || '' // Use BotFather to get the token
const chatId = process.env.TELEGRAM_CHAT_ID || ''

/**
 * Sends a message to a specified Telegram chat using the Telegram Bot API.
 *
 * @param {string} message - The message text to send.
 * @param {any} [object] - Optional object to include in the message. It will be stringified and appended to the message.
 * @returns {Promise<void>} - A promise that resolves when the message is successfully sent.
 * @throws Will throw an error if the message fails to send.
 */
export async function sendTelegramMessage(
  message: string,
  object?: any,
): Promise<void> {
  // Construct the URL for the Telegram Bot API
  const url = `https://api.telegram.org/bot${botToken}/sendMessage`

  // Prepare the message text, including the optional object if provided
  const text = object
    ? `${message}\n\n${JSON.stringify(object, null, 2)}`
    : message

  try {
    // Send the message using the fetch API
    const response = await fetch(url, {
      method: 'POST', // Specify the HTTP method
      headers: {
        'Content-Type': 'application/json', // Set the content type to JSON
      },
      body: JSON.stringify({
        chat_id: chatId, // Specify the chat ID
        text: text, // Include the message text
      }),
    })

    // Check if the response is not OK and throw an error if so
    if (!response.ok) {
      throw new Error(
        `Error sending message to Telegram: ${response.statusText}`,
      )
    }
  } catch (error) {
    // Log the error to the console or rethrow it
    console.error('Error sending message to Telegram:', error)
  }
}
  1. Retrieve the bot token from BotFather.
  2. Send your bot a message to get the chat ID.
  3. You can retrieve the chat ID from this endpoint: https://api.telegram.org/bot<bot_token>/getUpdates
  4. Set the bot token and chat ID as environment variables in your project.

How you can use it

Just call the function sendTelegramMessage with a message and an optional object. For example the error object.

try {
  // some code that might throw an error
} catch (error) {
  sendTelegramMessage('Error occurred', { error: 'User creation failed' })
}

Conclusion

This function lets me drop a quick notification anywhere I detect a bad result. For example, if my code logs that user creation didn't succeed, it calls sendTelegramMessage with a summary of the issue. My phone buzzes, and I know something went wrong.
That's all I need to keep tabs on vital checks. I never miss a glitch. This approach lifts my confidence in the overall system since I know I'll get a heads-up right away.