STM32 power down procedure
The best solution (assuming this is a soft power button monitored by the MCU) is probably to not actually turn it off, but to put the device into one of it's low power modes so that your volatile memory is maintained. There are applications that use sleep modes to get months of life out of pretty small batteries, it's just a matter of optimizing your code for power savings.

If this is a hard power button (meaning that it actually removes power from the MCU) then you could use a supercapacitor to keep the MCU running for a few seconds after power off. Read the state of the power supply before the supercap on one of the GPIOs and if it ever goes low that means power has been turned off and it's time to store everything before the supercap gets fully drained.