The fast-growing field of bioelectronic medicine aims to develop engineered systems that can relieve clinical conditions by stimulating the peripheral nervous system1–5. This type of technology relies largely on electrical stimulation to provide neuromodulation of organ function or pain. One example is sacral nerve stimulation to treat overactive bladder, urinary incontinence and interstitial cystitis (also known as bladder pain syndrome)4,6,7. Conventional, continuous stimulation protocols, however, can cause discomfort and pain, particularly when treating symptoms that can be intermittent (for example, sudden urinary urgency)8. Direct physical coupling of electrodes to the nerve can lead to injury and inflammation9–11. Furthermore, typical therapeutic stimulators target large nerve bundles that innervate multiple structures, resulting in a lack of organ specificity. Here we introduce a miniaturized bio-optoelectronic implant that avoids these limitations by using (1) an optical stimulation interface that exploits microscale inorganic light-emitting diodes to activate opsins; (2) a soft, high-precision biophysical sensor system that allows continuous measurements of organ function; and (3) a control module and data analytics approach that enables coordinated, closed-loop operation of the system to eliminate pathological behaviours as they occur in real-time. In the example reported here, a soft strain gauge yields real-time information on bladder function in a rat model. Data algorithms identify pathological behaviour, and automated, closed-loop optogenetic neuromodulation of bladder sensory afferents normalizes bladder function. This all-optical scheme for neuromodulation offers chronic stability and the potential to stimulate specific cell types. A closed-loop implantable bioelectronic device that can modulate peripheral neuronal activity is used to improve bladder function in a rat model of cystitis.