In order to elucidate the origin of spin in both dark matter and baryons in galaxies , we have performed hydrodynamical simulations from cosmological initial conditions . We study atomic cooling haloes in the redshift range 100 > z > 9 with masses of order 10 ^ { 9 } { M _ { \odot } } at redshift z = 10 . We assume that the gas has primordial composition and that { H _ { 2 } } -cooling and prior star-formation in the haloes have been suppressed . We present a comprehensive analysis of the gas and dark matter properties of four halos with very low ( \lambda \approx 0.01 ) , low ( \lambda \approx 0.04 ) , high ( \lambda \approx 0.06 ) and very high ( \lambda \approx 0.1 ) spin parameter . Our main conclusion is that the spin orientation and magnitude is initially well described by tidal torque linear theory , but later on is determined by the merging and accretion history of each halo . We provide evidence that the topology of the merging region , i.e . the number of colliding filaments , gives an accurate prediction for the spin of dark matter and gas : halos at the center of knots will have low spin while those in the center of filaments will have high spin . The spin of a halo is given by \lambda \approx 0.05 \times \left ( \frac { 7.6 } { number of filaments } % \right ) ^ { 5.1 } .