Get form_key with javascript in Magento 2.0?

Get form_key with javascript in Magento 2.0?

July 6, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Get form_key with javascript in Magento 2.0?

Retrieving the Form Key from Magento 2.0 for Custom Login Pages

As a developer new to Magento, you’re facing a common challenge when trying to create a custom login page outside of the platform: obtaining the form_key value required for secure form submissions. In this post, we’ll explore two approaches to achieve this—one using JavaScript and another with PHP—and provide best practices for a robust solution.

Understanding the Form Key in Magento

The form_key is a crucial security measure introduced in Magento 2.0 to prevent Cross-Site Request Forgery (CSRF) attacks by ensuring that form submissions originate from valid pages within your store. It’s generated as a random string and tied to each user session.

Retrieving the Form Key with JavaScript

Current Approach: XHR to Fetch the Entire Page

Your initial solution uses an XMLHTTPRequest to fetch the entire Magento homepage, parse its DOM, and extract the form_key value. While this approach works in a local development environment, it raises several concerns:

  1. Performance Issues: Loading the entire page for a single form key is inefficient.
  2. Security Risks: Exposing your store’s content to external scripts.
  3. Maintenance Challenges: Changes in Magento’s layout might break your script.

Improved JavaScript Solution: Direct API Endpoint

Instead of fetching an entire page, create a dedicated API endpoint within Magento that returns the current form_key value as JSON:

  1. Create a new controller under app/code/Vendor/Module/Controller/Local/Formkey.php.
namespace Vendor\Module\Controller\Local;

use Magento\Framework\App\Action;
use Magento\Framework\App\ResponseInterface;

class FormKey extends Action
{
    public function execute(): ResponseInterface
    {
        $formKey = $this->_request->getSession()->getFormKey();
        return $this->jsonResponse(['form_key' => $formKey]);
    }
}
  1. Add the following route in app/code/Vendor/Module/etc/frontend/routes.xml:
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App etc/routes.xsd">
    <route id="vendor_formkey_index_index">
        <frontName>vendor</frontName>
        <action>\Vendor\Module\Controller\Local\FormKey::execute</action>
    </route>
</routes>
  1. Fetch the form_key in your JavaScript:
fetch('https://your-magento-site.com/vendor/formkey/index')
  .then(response => response.json())
  .then(data => {
    const formKey = data.form_key;
    console.log(formKey);
    // Pass the form key to your custom login page
  });

Benefits of this Approach

  • Direct and efficient API access.
  • Minimal performance impact compared to fetching an entire page.
  • Improved security by limiting exposed data.
  • Easier maintenance and scalability.

Retrieving the Form Key with PHP: A Note on Security

While you mentioned being open to creating a PHP file within Magento to generate the form_key, it’s crucial to stress that this approach introduces significant security risks. Generating sensitive data like form keys in an accessible external PHP file is a serious vulnerability, as it exposes your Magento install to potential attackers.

Conclusion: Choosing the Right Approach for Your Needs

For most use cases, especially in production environments, I strongly recommend implementing the JavaScript solution using a dedicated API endpoint within Magento. This approach offers the best balance between security, performance, and maintainability.

However, if you’re working on a local development environment or need to access form keys programmatically from PHP scripts within your project, consider the following:

  1. Implement the API-based JavaScript solution for your custom login page.
  2. For internal PHP use-cases only (never expose this in production), create a controller similar to the one described above and access it securely through Magento’s built-in routing system.

Remember that form keys are sensitive data designed to protect your store from malicious attacks, so always prioritize security when handling them in your custom integrations.

Magento 2 Performance Security API

Our network