The μ-opioid receptor (μOR), a prototypical member of the G protein-coupled receptor (GPCR) family, is the molecular target of opioid analgesics such as morphine and fentanyl. Due to the limitations and severe side effects of currently available 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, are emerging as 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 solving 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 inserts into the μOR and centers most binding contacts, we design short peptide analogues that retain μOR antagonism. The work illustrates the potential of nanobodies to uniquely engage with GPCRs and describes novel μOR ligands that can serve as a basis for therapeutic developments.