Why Form Key is added in every page In Magento 2 as a hidden input type.

<input type="hidden" value="dEOXfL0kxDc8W4Yt" name="form_key">

I observed how it is generated. Is there any specific reason for adding this ?

I found the related question here but no answer.

Any help.


Form keys in Magento are a means of preventing against Cross Site Request Forgery, in short, it's to keep you safe from people trying to post to your forms (like add to cart) from other sites posing as you.

This can be dangerous because someone could theoretically create their own form and post to any form handler controller action in your store. CSRF protection essentially ignores any post which fail a check on the included form_key parameter with the form post.

<?php echo $this->getBlockHtml('formkey')?>

It tells Magento to look for a layout block with the name "formkey" and output it. In Magento this is usually some file which has this in it:

<div><input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" /></div>

This instructs Magento to output and store a unique form key for a user session. All CSRF-protected Magento controller actions will verify against this before doing anything of value.

All Menu Items have an additional URL parameter named key, with a corresponding value


This special code is required for all URLs, and is here to help prevent cross site script attacks. If you fail to include this key with your URL, Magento will reject the request as invalid.

This URL key is why we need to create a Menu Item in the first place — without Magento generating a URL key for us, there’s no simple safe way to access a standard admin controller.

| improve this answer | |
  • Yes for forms it is fine but i observed the key in all pages those do not contain any forms. – Krishna ijjada Sep 13 '16 at 5:34
  • you can read i have added some more lines in my ans. – Arjun Sep 13 '16 at 5:44

You can add formkey by this code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$FormKey = $objectManager->get('Magento\Framework\Data\Form\FormKey'); 

<!-- Hidden form key field after <form> tag -->
<input name="form_key" type="hidden" value="<?php echo $FormKey->getFormKey();?>">
| improve this answer | |
  • I created a custom form in my own template and it works, thanks! – hayatbiralem May 14 '18 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.