The μ-opioid receptor (μOR), a prototypical G protein-coupled receptor (GPCR), is the target of opioid analgesics such as morphine and fentanyl. Due to the severe side effects of current opioid drugs, there is considerable interest in developing novel modulators of μOR function. Most GPCR ligands today are small molecules, however biologics, including antibodies and nanobodies, represent alternative therapeutics with clear advantages such as affinity and target selectivity. Here, we describe the nanobody NbE, which selectively binds to the μOR and acts as an antagonist. We functionally characterize NbE as an extracellular and genetically encoded μOR ligand and uncover the molecular basis for μOR antagonism by determining the cryo-EM structure of the NbE-μOR complex. NbE displays a unique ligand binding mode and achieves μOR selectivity by interactions with the orthosteric pocket and extracellular receptor loops. Based on a β-hairpin loop formed by NbE that deeply protrudes into the μOR, we design linear and cyclic peptide analogs that recapitulate NbE’s antagonism. The work illustrates the potential of nanobodies to uniquely engage with GPCRs and describes lower molecular weight μOR ligands that can serve as a basis for therapeutic developments.