The synthesis of nucleobases in natural environments, especially in interstellar molecular clouds, is the focus of a long-standing debate regarding prebiotic chemical evolution. Here we report the simultaneous detection of all three pyrimidine (cytosine, uracil and thymine) and three purine nucleobases (adenine, xanthine and hypoxanthine) in interstellar ice analogues composed of simple molecules including H2O, CO, NH3 and CH3OH after exposure to ultraviolet photons followed by thermal processes, that is, in conditions that simulate the chemical processes accompanying star formation from molecular clouds. Photolysis of primitive gas molecules at 10 K might be one of the key steps in the production of nucleobases. The present results strongly suggest that the evolution from molecular clouds to stars and planets provides a suitable environment for nucleobase synthesis in space.