Interstitial nitrides and carbides of early transition metals in groups IV–VI exhibit platinum-like electronic structures, which make them promising candidates to replace noble metals in various catalytic reactions. Herein, we present the preparation and characterization of nano-sized transition metal nitries and carbides of groups IV–VI (Ti, V, Nb, Ta, Cr, Mo, and W) using mesoporous graphitic carbon nitride (mpg-C3N4), which not only provides confined spaces for restricting primary particle size but also acts as a chemical source of nitrogen and carbon. We studied the reactivity of the metals with the template under N2 flow at 1023 K while keeping the weight ratio of metal to template constant at unity. The produced nanoparticles were characterized by powder X-ray diffraction, CHN elemental analysis, nitrogen sorption, X-ray photoelectron spectroscopy, and transmission electron microscopy. The results show that Ti, V, Nb, Ta, and Cr form nitride phases with face centered cubic structure, whereas Mo and W forme carbides with hexagonal structures. The tendency to form nitride or carbide obeys the free formation energy of the transition metal nitrides and carbides. This method offers the potential to prepare the desired size, shape and phase of transition metal nitrides and carbides that are suitable for a specific reaction, which is the chief objective of materials chemistry.