In general, if $f\circ g$ is an injective function, then $g$ is an injective function, and if $f\circ g$ is a surjective function, then $f$ is a surjective function. In our case, $f\circ g=Id$ gives that $g$ is an injective function and $f$ is a surjective function. If $X$ is a finite set, injectivity implies surjectivity, hence $g$ is a bijective map and $f\circ g(x)=x$ implies $f(x)=g^{-1}(x)$, from which $g\circ f=Id$ follows.
However, if $X$ is not a finite set we have counter-examples. For instance, we may take an injective map $g:[0,1]\to[0,1)$ and a surjective map $f$ for which $f(1)=1$ and $f([0,1))=[0,1]$ - just to be clear, $g$ removes a point from an interval and $f$ add it back - such that $f\circ g$ is the identity over $X=[0,1]$. In such a case, however, $1$ does not belong to $g\circ f(X)$, hence $g\circ f$ cannot be the identity over $X$.