Abstract Formation of halos in the dark ages from initial spherical perturbations is analyzed in a four-component universe (dark matter, dark energy, baryonic matter, and radiation) in the approximation of relativistic hydrodynamics. Evolution of density and velocity perturbations of each component is obtained by integration of a system of nine differential equations from z = 108 up to virialization, which is described phenomenologically. It is shown that the number density of dark matter halos with masses M ∼ 108–109 M ⊙ virialized at z ∼ 10 is close to the number density of galaxies in comoving coordinates. The dynamical dark energy of classical scalar field type does not significantly influence the evolution of the other components, but dark energy with a small value of effective sound speed can affect the final halo state. Simultaneously, the formation/dissociation of the first molecules has been analyzed in the halos that are forming. The results show that number densities of molecules H2 and HD at the moment of halo virialization are ∼103 and ∼400 times larger, respectively, than on a uniformly expanding background. This is caused by increased density and rates of reactions at quasi-linear and nonlinear evolution stages of density and velocity of the baryonic component of halos. It is shown also that the temperature history of the halo is important for calculating the concentration of molecular ions with low binding energy. Hence, in a halo with virial temperature ∼105 K the number density of the molecular ion HeH+ is approximately 100 times smaller than that on the cosmological background.