Node-red flow detection of change server IP

I don’t have a static IP address from my ISP, which occasionally makes my Home Assistant (HA) inaccessible through my custom domain name. To address this, I created a flow in Node-Red that checks every two hours to see if the IP has changed. At present, it notifies me via a Telegram message, but it could also be configured to connect to the REST API of your domain provider.

Small and simple, but maybe usefull to others in this community.

The flow

  1. Timestamp to start every two hours or internal to your choice;
  2. Retrieve IP of server (Node-red is on same server as HA) trough a service provider, for example https://api64.ipify.org;
  3. Check the IP
  4. Send message if a new IP has been detected;

Code of function node

// Retrieve the last stored IP, defaulting to "0" if not set
var lastIP = global.get('lastIP') || "0";
var currentIP = msg.payload;

// Check if the current IP is different from the last stored IP
if (currentIP !== lastIP) {
    // If different, store the new IP and prepare a message about the new IP
    global.set('lastIP', currentIP);
    msg.payload = {
        chatId: '#ID',
        type: 'message',
        content: 'New IP address detected: ' + currentIP
    };
} else {
    // If the IP is the same, you can choose to do nothing or send a message
    // For this example, we'll do nothing
    return null; // Stops the flow, so no message is sent
}

return msg;