The oldest reference to this tradition that I am aware of is the Taz ("Turei Zahav"), by David haLevi Segal, 17th c.
הלוחש על המכה או על החולה ורוקק ואחר כך קורא פסוק מן התורה אין לו חלק
לעוה"ב
One who whispers over a wound or over a sick person and who spits, and
who then recites a verse from the Torah has no portion in the world to
come.
ורוקק ואח"כ קורא כו'. הטעם דכיון דמזכיר שם שמים על הרקיקה הוי בזיון ח"ו ועל כן אין להקשות ממה שנוהגין ברקיקה קודם ואנחנו כורעים דשם
הכל יודעין שהרקיקה היא לבזיון הגילולים של עובדי כוכבים והיא כבוד שמים
שמזכיר אח"כ
... and who spits, and who then, etc: The reason is that since he mentions the name of heaven after spitting it is a disgrace, God forbid.
Therefore, one need not find problematic our custom of spitting before
"and we bow" [ve'anachnu kor'im, in Aleynu Leshabeach], for there
everybody knows that the spitting is meant as a degradation of the idols of
star worshippers, but that it is the honour of heaven that we are
mentioning afterwards.
I know of no text that gives a specific reason as to why it's done, but it is practised outside hasidic circles as well. It is mentioned, for example, in Siddur Vilna, p138:
ונוהגין לרוק בשעה שאומר שהם משתחוים להבל וריק וכו
We have a custom to spit when one says, "For they prostrate themselves
to idleness and emptiness", etc.
I have heard it said that this is because "and emptiness" (וריק) looks similar to "to spit" (לרוק), but this is less of an origin story than it is a justification. In any case, to quote Hamlet, this may be a custom more honoured in the breach than the observance.