Magento 2.3: Empty FormKey on Early Page Load

Gabriel Somoza
1 min readAug 24, 2020

--

I recently run into a situation where we had a custom piece of code that needed a Form Key as soon as possible after page load.

However the first request to Magento doesn’t set the form_key cookie for first time visitors that land on a page that’s cached. Our KnockoutJS component, which was being loaded as early as possible, received an empty value when trying to read from windows.FORM_KEY or even document.cookie .

After some debugging I found out that the form_key cookie is being generated by the frontend using this script: vendor/magento/module-page-cache/view/frontend/web/js/page-cache.js

The solution was to make our KnockoutJS component depend on pageCache, essentially instructing RequireJS to not load our component until pageCache was first loaded.

--

--