TypeError: Cannot read properties of undefined (reading 'notification')

On a function I have this two Ifs:

if (typeof msg.payload.notification !== 'undefined') {...}
if (typeof msg.payload.data.data.item.title !== 'undefined') {...}

But I get the Error TypeError: Cannot read properties of undefined (reading 'notification')

What did I wrong? How should I do it better?

Either your msg doesn't have a payload or you have deleted it.

What is in the rest of the function? Specifically above that code?

Try adding node.warn(["msg",msg]) before that code to see what is actually inside msg

I resceive diferent message from an external source. So in this function I separate the kind of messages and react on it. I know that there are messages without a payload.

If you are know you can get messages without a payload, then that is why you get the error TypeError: Cannot read properties of undefined (reading 'notification')

It is literally saying "Cannot read notification from nothing" - so you must guard against trying to access notification if its source is empty

e.g...

//GUARD: check that msg.payload is SOMETHING before trying to read its properties...
if(typeof msg.payload == "object") {
    if (typeof msg.payload.notification !== 'undefined') {...}
     //GUARD: check that msg.payload.data.data.item is SOMETHING before trying to read its properties...
    if (msg.payload.data && msg.payload.data.data && msg.payload.data.data.item) {
        if (typeof msg.payload.data.data.item.title !== 'undefined') {...}
        //...
        //etc
    }
    //...
    //etc
}

Thanks a lot @Steve-Mcl I was not aware that Nodered is that picky about missing content. Your answer was Helpfull !

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.