The perception of pain as an alarm signal is primarily processed by nociceptive transmission from the dorsal horn of the spinal cord (DHSC) to the brain. Descending pathways from the brainstem dynamically modulate this process, either facilitating or inhibiting nociceptive information based on physiological, emotional, genetic and environmental factors. Among these pathways, serotonergic neurons of the nucleus raphe magnus (NRM) play a critical role in nociceptive modulation, though their precise mechanisms of action remain elusive. Here we aimed to resolve this longstanding question. We investigated NRM serotonergic modulation of pain using imaging, behavioral, pharmacological, electrophysiological, chemogenetic and optogenetic approaches. We discovered that NRM serotonin neurons mediate bidirectional effects on nociception depending on the pattern of activation. Brief optogenetic stimulation induced analgesia, whereas prolonged stimulation paradoxically led to hyperalgesia. Mechanistically, we identified spinal inhibitory interneurons as the principal targets of NRM serotonergic inputs, with three distinct receptor subtypes underpinning bidirectional modulation. Furthermore, our model explains heightened pain perception via pathological NRM serotonin neuron hyperexcitability acting at 5-HT3 receptors. Targeting the activity of serotonin neurons within physiological ranges represents a promising therapeutic strategy for managing pain and preventing its chronic exacerbation; a finding of significance considering the opioid-based treatment crisis.