How can I prevent the nuts in my shelving from coming loose?
If you use a product known generically as anaerobic thread locker, you will prevent the rotation of the fastener unless it is done by a wrench. Locktite™ is one such brand name, although many other names abound. Do not use the red version, as it is nearly permanent, requiring application of intense heat to release. Blue is medium and holds well under vibration, while green is considered low strength. For your application, one would expect even green will work well, although in my experience it is rare to see it on the shelf. You can find threadlocker in red and blue at most auto parts stores and certainly in a well stocked hardware store.

Until I read the Loctite page, I wasn't aware there is also purple threadlock.

As noted in the text from the web site, use caution on selecting the product. The packaging/bottle color is not a good indication of the holding strength.