Scientific information about how magnesium works is hard to come by. Here's what I have been able to gather from various sources: The cells in your body need calcium to go into "on state". To go into "off state" magnesium has to go in and displace calcium.
When your body is low on magnesium your muscles can't go into "off state" and your muscles become stiff. To relax you need an Epsom salt bath (it contains magnesium) or just take magnesium supplements.
When your brain cells can't go to "off state" you can't sleep. You need magnesium to help your brain cells go into off state. However the "blood brain barrier" (look it up) prevents magnesium from easily entering the brain. Magnesium l-threonate (that's a compound of magnesium, not a brand name) can pass through this barrier and help you sleep.
I have had sleep issues for many years. I saw many doctors including sleep specialists but all they wanted to do is put me on prescription meds. But these meds are addictive and you have to take it for the rest of your life. I didn't want that. These are "quick fixes". As a software developer I was interested in finding the underlying problem and fix that, as opposed to the quick fixes that the medical community was offering me.
A breakthrough came when I saw a naturopathic doctor for my stiff muscles and she advised me to take Epsom salt baths. That seemed to help. I investigated more and found out that the ingredient in Epsom salt that helped me is magnesium. Then I found out that you can actually get magnesium pills and tried that. That worked remarkably well. But the big surprise was that I slept better the night I tried the magnesium pill. Since then I have been researching how it is that magnesium helped me sleep.
Stress depletes magnesium in your body. If you are a software developer you are stressing your brain all day when you do your job and you are depleting magnesium. Low magnesium levels causes muscle issues as well as sleep issues. Magnesium supplements solve the problem.
It is very unfortunate that medical doctors don't seem to be very knowledgeable about this topic. When I see doctors I mention that I am taking magnesium for muscle and sleep issues and they seem surprised, but no doctor has yet told me that I am wrong.
Note that magnesium is a natural mineral, not a drug, essential for your body, and found in many foods. Excess amounts of magnesium can cause a laxative effect, but this is very temporary.