you need to declare msg.headers as an object add
msg.headers = {};
before the other references to msg.headers.