Corticostriatal projection neurons from prelimbic medial prefrontal cortex to the nucleus accumbens core critically regulate drug-seeking behaviors, yet the underlying encoding dynamics whereby these neurons contribute to drug seeking remain elusive. Here we use two-photon calcium imaging to visualize the activity of corticostriatal neurons in mice from the onset of heroin use to relapse. We find that the activity of these neurons is highly heterogeneous during heroin self-administration and seeking, with at least 8 distinct neuronal ensembles that display both excitatory and inhibitory encoding dynamics. These neuronal ensembles are particularly apparent during relapse, where excitatory responses are amplified compared to heroin self-administration. Moreover, we find that optogenetic inhibition of corticostriatal projection neurons attenuates heroin seeking regardless of the relapse trigger. Our results reveal the precise corticostriatal activity dynamics underlying drug-seeking behaviors and support a key role for this circuit in mediating relapse to drug seeking.