This is from Lecture Notes in Algebraic Topology, 2nd by Davis and Kirk.
My try of the direct proof involves a step $$h\circ g\circ f=h\circ f\implies g=\mathrm{id}$$ for which a counterexample can be found in the category $\mathbf{Set}$.
How should I bypass this?

I don't know how you got to the equality you write; unless you have some compositions written on the wrong side by mistake... Since you don't show the derivation, I can't really comment on whether one can fix your approach, or if there is some simple error in it.
Anyway...
This is a typical situation. Consider what the universal property of the product gives you about both $(X,\pi_1,\pi_2)$ and $(X',\pi_1',\pi_2')$:
Now, by 3 and 2, there exists a (unique) morphism $h\colon X'\to X$ such that $\pi_i' = \pi_i\circ h$.
And by 1 and 4, there exists a (unique) morphism $k\colon X\to X'$ such that $\pi_i = \pi_i'\circ k$.
Now, consider $k\circ h\colon X'\to X'$. Note that $\pi_i'\circ (k\circ h)=(\pi_i'\circ k)\circ h = \pi_i\circ h = \pi_i'$. However, using 3 and 4, we know that there is a unique morphism $j\colon X'\to X'$ such that $\pi_i' = \pi_i'\circ j$. Now, clearly $\mathrm{id}_{X'}$ works; but then so does $k\circ h$ by our computations. So the uniqueness clause of the universal property implies that we must have $k\circ h = \mathrm{id}_{X'}$. A similar argument should be used to show that $h\circ k = \mathrm{id}_{X}$.