Postoperative depression (POD) and postoperative cognitive dysfunction (POCD) have placed heavy burden on patients’ physical and mental health in recent years. Sleep disturbance before surgery is a common phenomenon that has been increasingly believed to affect patients’ recovery, especially in aged patients, while little attention has been paid to sleep disruption before surgery and the potential mechanism remains ambiguous. Ketamine has been reported to attenuate POCD after cardiac surgery and elicit rapid-acting and sustained antidepressant actions. The present study aimed to clarify the effect of esketamine’s (the S-enantiomer of ketamine) protective effects and possible mechanisms of action in POCD and POD. Our results showed that sleep disturbance before surgery exacerbated microglial M1 polarization and microglial BDNF-TrkB signalling dysfunction induced by surgery, resulting in postoperative emotional changes and cognitive impairments. Notably, treatment with esketamine reversed the behavioural abnormalities through inhibiting the M1 polarization of microglia and the inflammatory response thus improving BDNF-TrkB signalling in vivo and vitro. In addition, esketamine administration also reversed the impaired hippocampal synaptic plasticity which has been perturbed by sleep disturbance and surgery. These findings warrant further investigations into the interplay of esketamine and may provide novel ideas for the implication of preoperative preparations and the prevention of postoperative brain-related complications.