A reliable method for recording evoked synaptic events in identified neurons in Caenorhabditis elegans would greatly accelerate our understanding of its nervous system at the molecular, cellular and network levels. Here we describe a method for recording synaptic currents and potentials from identified neurons in nearly intact worms. Dissection and exposure of postsynaptic neurons is facilitated by microfabricated agar substrates, and ChannelRhodopsin-2 is used to stimulate presynaptic neurons. We used the method to analyse functional connectivity between a polymodal nociceptor and a command neuron that initiates a stochastic escape behaviour. We find that escape probability mirrors the time course of synaptic current in the command neuron. Moreover, synaptic input increases smoothly as stimulus strength is increased, suggesting that the overall input–output function of the connection is graded. We propose a model in which the energetic cost of escape behaviours in C. elegans is tuned to the intensity of the threat.