It is also possible that the viruses and bacteria of new planets are so alien to folks from off-world and their alien biology that they don't affect them. The viruses and bacteria of a planet have evolved to act within that particular ecosystem not the alien one that is a Klingon, human, or any other off world visitor. No magic involved whatsoever.
That could be true in some cases, but there are many, many examples where the characters are shown to be able to eat the local food (and a few cases where the locals ate them!). I won't use the examples of species interbreeding since presumably we're only talking about new unexplored worlds.
It's a little unlikely that macroscopically the biosphere would evolve to be compatible and microscopically it wouldn't.
I suppose a transporter could keep a reference matrix for each transportee, and then filter out what didn't match that. But how would they allow for mental changes? How would they prevent a memory wipe every time you beamed back from a planet? It would also make acquiring tattoos a waste of time. OTOH, perhaps such technology could be used to counter the ageing process.
These things have all been shown onscreen, except for the tattoo example.
Anyway, the answer is
it is magic. That's what I was afraid of.
You sound surprised. Trek is not hard s.f. and never has been. It's riddled with this stuff.