Context. Cytosine, thymine, and uracil are three of the five primary nucleobases that function as the fundamental units of the genetic code in nucleic acids. In searching the extraterrestrial origins of microscopic life, previous studies have reported formation routes of nucleobases in interstellar ice analogs. The present work explores the possibility that nucleobases could form from small molecules through gas-phase reactions in the interstellar medium (ISM). Aims. We aim to search energetically favorable synthetic routes toward the formation of cytosine, thymine, and uracil via gas-phase reactions, using first principles calculations. Based on the computation of a reaction energy barrier and reactant formation energy, we tried to identify the specific interstellar environments favorable to the formation of the nucleobases, with respect to the previously reported detection of relevant reactants in the ISM. Methods. Density functional theory calculations were carried out to investigate the chemical reaction pathways using the M06 functional with 6-31+G(d,p)/6-311++G(d,p) basis sets. An ab initio Møller-Plesset perturbation theory in the second order (MP2) was also used to corroborate the results. Results. We report synthetic routes toward the formation of cytosine, thymine, and uracil through gas-phase reactions between partially dehydrogenated formamide (H2NCHO) and vinyl cyanide (H2CCHCN). The most energetically favorable pathway to the formation of 1H-pyrimidin-2-one (C4H4N2O), a direct precursor of nucleobases, was found in a molecule-radical reaction between HNCHO and H2CCHCN, with an energy barrier of 19.3 kcal mol−1. The energy barriers for the optimal reaction pathways between C4H4N2O and amino, methyl, or hydroxyl to finally produce cytosine, thymine, or uracil are about 11.3, 18.6, or 19.9 kcal mol−1, respectively. Conclusions. The optimal energy barriers of 19.3 and 23.8 kcal mol−1 roughly correspond to a reaction rate coefficient of 10−11 cm3 s−1 at 180 and 220 K, respectively. This indicates that the reaction could be thermally feasible through a gas-phase reaction in hot molecular cores or in the inner part of the protoplanetary disks. In contrast, the energy barriers for the reactions between other dehydrogenated radicals and molecules are relatively high, which corresponds to the extinction energy of far-ultraviolet photons in photo-dissociation regions. Furthermore, the computed pathways suggest that prior H migration in the reactants could be the key rate-determining process for the synthesis of the primary nucleobases.