> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gr4vy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Adding secure fields

The next step to is to add **Secure Fields** to your checkout experience.

## Install Secure Fields

There are a few ways to install **Secure Fields**, either as a React component,
Node library, or straight off the CDN.

<CodeGroup>
  ```bash React theme={"system"}
  npm install @gr4vy/secure-fields-react --save
  # or: yarn add @gr4vy/secure-fields-react
  ```

  ```bash Node theme={"system"}
  npm install @gr4vy/secure-fields --save
  # or: yarn add @gr4vy/secure-fields
  ```

  ```html CDN theme={"system"}
  <script src="https://cdn.{instance_id}.gr4vy.app/secure-fields/latest/secure-fields.js"></script>
  <link
    rel="stylesheet"
    href="https://cdn.{instance_id}.gr4vy.app/secure-fields/latest/secure-fields.css"
  />
  ```
</CodeGroup>

<Note>
  When using the CDN the latest version of the library is always pulled straight
  from the server for every request.
</Note>

## Initializing secure fields

With **Secure Fields** installed it's now possible to initialize the connection
to your instance.

**Secure Fields** expects the ID of your instance (`gr4vyId`), the
environment, and a checkout session ID.

<Note>
  The instance ID is the unique identifier for the deployment of the system and is included in every API call.
  Together with the environment (sandbox or production) it is used to connect to the right APIs, as well as dashboard.
</Note>

<CodeGroup>
  ```jsx React theme={"system"}
  import '@gr4vy/secure-fields-react/lib/style.css'
  import { SecureFields } from "@gr4vy/secure-fields-react";

  const App = () => {
    return (
      <SecureFields
        // set up the environment
        gr4vyId="example"
        environment="sandbox"
        sessionId={sessionId} // created in step 2
        // enable debugging
        debug
        // attach event handlers
        onReady={(data) => console.warn("Secure Fields loaded", data)}
        onCardVaultSuccess={() =>
          console.warn("Card has been tokenized successfully!")
        }
        onCardVaultFailure={() => console.error("Failed to tokenize card data")}
      >
        {/* Form to be added next */}
        <Form />
      </SecureFields>
    );
  };
  ```

  ```js Node theme={"system"}
  import SecureFields from "@gr4vy/secure-fields";

  // set up the environment
  const gr4vyId = "example";
  const environment = "sandbox";
  const sessionId = "..."; // created in step 2
  // initialize the SDK
  const secureFields = new SecureFields({
    gr4vyId,
    environment,
    sessionId,
  });
  // enable debugging
  secureFields.setDebug(true);
  ```

  ```js CDN theme={"system"}
  // set up the environment
  const gr4vyId = "example";
  const environment = "sandbox";
  const sessionId = "...";
  // initialize the SDK
  const secureFields = new SecureFields({
    gr4vyId,
    environment,
    sessionId,
  });
  // enable debugging
  secureFields.setDebug(true);
  ```
</CodeGroup>

## Adding each of the individual fields

Next, add any of the 3 individual fields to the form. Mix and
match these with custom forms, and add custom labels.

<CodeGroup>
  ```jsx React theme={"system"}
  import {
    CardNumber,
    ExpiryDate,
    SecurityCode,
  } from '@gr4vy/secure-fields-react'

  const Form = () => {
    return (
      // Custom fields can be added as well as secure fields
      <label htmlFor="cc-holder-name">Name</label>
      <input
        id="cc-holder-name"
        placeholder="Name on the card"
      />

      // These are secure fields
      <label htmlFor="cc-number">Card Number</label>
      <CardNumber placeholder="Enter card number" />

      <label htmlFor="cc-expiry-date">Expiry Date</label>
      <ExpiryDate placeholder="Enter expiry date" />

      <label htmlFor="cc-security-code">Security Code</label>
      <SecurityCode placeholder="Enter security code" />

      <button id='cc-button'>Store card data</button>
    )
  }
  ```

  ```html Node theme={"system"}
  {/* You can add your own fields as well as secure fields */}
  <label for="cc-holder-name">Name</label>
  <input id="cc-holder-name" placeholder="Name on the card" />

  {/* These are secure fields */}
  <label for="cc-number">Card Number</label>
  <input id="cc-number" />

  <label for="cc-security-code">Security Code</label>
  <input id="cc-security-code" />

  <label for="cc-expiry-date">Expiry date</label>
  <input id="cc-expiry-date" />

  <button id="cc-button">Store</button>

  <script>
    // Add fields via the addField method
    const cardNumberField = secureFields.addCardNumberField("#cc-number", {
      placeholder: "Enter card number",
    });

    const securityCodeField = secureFields.addSecurityCodeField(
      "#cc-security-code",
      {
        placeholder: "Enter security code",
      }
    );

    // Alternatively an HTML element can be passed directly
    const expiryDateField = secureFields.addExpiryDateField(
      document.querySelector("#cc-expiry-date"),
      {
        placeholder: "Enter expiry date",
      }
    );
  </script>
  ```

  ```html CDN theme={"system"}
  {/* You can add your own fields as well as secure fields */}
  <label for="cc-holder-name">Name</label>
  <input id="cc-holder-name" placeholder="Name on the card" />

  {/* These are secure fields */}
  <label for="cc-number">Card Number</label>
  <input id="cc-number" />

  <label for="cc-security-code">Security Code</label>
  <input id="cc-security-code" />

  <label for="cc-expiry-date">Expiry date</label>
  <input id="cc-expiry-date" />

  <button id="cc-button">Store</button>

  <script>
    // Add fields via the addField method
    const cardNumberField = secureFields.addCardNumberField("#cc-number", {
      placeholder: "Enter card number",
    });

    const securityCodeField = secureFields.addSecurityCodeField(
      "#cc-security-code",
      {
        placeholder: "Enter security code",
      }
    );

    // Alternatively an HTML element can be passed directly
    const expiryDateField = secureFields.addExpiryDateField(
      document.querySelector("#cc-expiry-date"),
      {
        placeholder: "Enter expiry date",
      }
    );
  </script>
  ```
</CodeGroup>

<Info>
  When not using the React SDK, every field Embed needs to be attached to an HTML element.
  In this case, the fields were attached to `<input>` fields. The fields can be attached to
  any element using a `querySelector`-compatible query.
</Info>

Other kinds of information can also be collected along with the card data. Postal code is currently supported as an additional field.

<CodeGroup>
  ```jsx React theme={"system"}
  import { Field } from '@gr4vy/secure-fields-react'

  <label htmlFor="postal-code">Postal code</label>
  <Field
    type="postalCode"
    placeholder="Enter postal code"
    pattern="[A-Z][0-9]\s[0-9][A-Z]{2}" // optional, defaults to 5 characters minimum
  />
  ```

  ```html Node theme={"system"}
  <label for="postal-code">Postal code</label>
  <input id="postal-code" />

  <script>
    const postalCodeField = secureFields.addField("#postal-code", {
      type: 'postalCode',
      placeholder: "Enter postal code",
      pattern: "[A-Z][0-9]\\s[0-9][A-Z]{2}" // optional, defaults to 5 characters minimum
    });
  </script>
  ```

  ```html CDN theme={"system"}
  <label for="postal-code">Postal code</label>
  <input id="postal-code" />

  <script>
    const postalCodeField = secureFields.addField("#postal-code", {
      type: 'postalCode',
      placeholder: "Enter postal code",
      pattern: "[A-Z][0-9]\\s[0-9][A-Z]{2}" // optional, defaults to 5 characters minimum
    });
  </script>
  ```
</CodeGroup>

Each secure field should now be loaded on the page. Please see the more
extensive guides on how to add [event listeners](/guides/payments/secure-fields/events) and
custom [styles](/guides/payments/secure-fields/theming) to **Secure Fields**.

## Vaulting the card data

**Secure Fields** handles the PCI-compliant submission of all the card data to
the servers. Once the form is ready, use the submit feature of
**Secure Fields** to vault the data. A callback notifies you when the data
has been submitted successfully.

<CodeGroup>
  ```jsx React theme={"system"}
  import { useSecureFields } from "@gr4vy/secure-fields-react";

  const Form = () => {
    const { secureFields } = useSecureFields();

    const onClick = () => {
      secureFields.submit();
    };
  };
  ```

  ```js Node theme={"system"}
  secureFields.addEventListener(SecureFields.Events.CARD_VAULT_SUCCESS, () => {
    console.log("Card successfully tokenized");
  });
  secureFields.addEventListener(SecureFields.Events.CARD_VAULT_FAILURE, () => {
    console.log("Card tokenization failed");
  });

  document.querySelector("#cc-button").addEventListener("click", () => {
    secureFields.submit();
  });
  ```

  ```js CDN theme={"system"}
  secureFields.addEventListener(SecureFields.Events.CARD_VAULT_SUCCESS, () => {
    console.log("Card successfully tokenized");
  });
  secureFields.addEventListener(SecureFields.Events.CARD_VAULT_FAILURE, () => {
    console.log("Card tokenization failed");
  });

  document.querySelector("#cc-button").addEventListener("click", () => {
    secureFields.submit();
  });
  ```
</CodeGroup>

<br />

<Warning>
  **Checkout session expiry**

  A checkout session is only valid for one hour. This means that the checkout
  session needs to be used to create a transaction or store the details as
  a payment method before that time.
</Warning>

## Summary

In this step you:

* Installed and initialized Secure Fields.
* Rendered each of the individual fields in a custom UI
* Submitted the data to the vault and listened for events
