Melatonin is a functionally conserved broad-spectrum physiological regulator that exists in most biological organisms in nature. Enrichment of tomato fruit with melatonin not only enhances its agronomic traits but also provides extra health benefits. In this study, we elucidate the full melatonin biosynthesis pathway in tomato fruit by identification of novel biosynthetic genes that encode caffeic acid O-methyltransferase 2 (SlCOMT2) and N-acetyl-5-hydroxytryptamine-methyltransferases 5/7 (SlASMT5/7). We further revealed that red light supplement has significantly enhanced melatonin content in tomato fruit. This induction relies on the “serotonin—N-acetylserotonin—melatonin” biosynthesis route via the SlphyB2-SlPIF4-SlCOMT2 module. Based on the regulatory mechanism, we targeted the binding motif of SlPIF4 in the promoter of SlCOMT2 to design the gene-editing strategy and significantly enhanced the production of melatonin in tomato fruit. Our study provides a good example of how the understanding of plant metabolic pathways responding to environmental factors can guide the engineering of new health-promoting food.