Importing Stripe.js as an ES Module
Tags: esnext, react, stripe, payments
Published: 2020-03-26 07:47:47

---
title: Importing Stripe.js as an ES Module
published: true
description: Learn how to import Stripe.js into your web application with the `stripe-js` module.
tags: esnext, react, stripe, payments
---

Stripe.js allows you to collect sensitive data, like credit card details, in a secure and PCI compliant manner. To make sure your application always uses the latest version and therefore stays [secure and compliant](https://stripe.com/docs/security#validating-pci-compliance), you must load Stripe.js directly from `https://js.stripe.com` rather than including it in a bundle or hosting it yourself.

This can be challenging when building modern web applications, for example with React and Vue, or in general server-side rendered applications, where you can't easily include a script tag.

That's why we provide a [`stripe-js` module](https://github.com/stripe/stripe-js#stripejs-es-module) which you can install via your package manager and import into your application to load Stripe.js in a compliant manner.

## Installation

Use `npm` or `yarn` to install the Stripe.js module:

```sh
npm install @stripe/stripe-js
# or
yarn add @stripe/stripe-js
```

## Usage

### `loadStripe`

This function returns a `Promise` that resolves with a newly created `Stripe` object once Stripe.js has loaded. If necessary, it will load Stripe.js for you by inserting the Stripe.js script tag. If you call `loadStripe` in a server environment it will resolve to `null`.

```js
import { loadStripe } from '@stripe/stripe-js';

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
```

Replace the test API key above with your [own publishable API key](https://dashboard.stripe.com/account/apikeys).

For more information on how to use Stripe.js once it loads, please refer to the [Stripe.js API reference](https://stripe.com/docs/js) or follow the [accept a payment guide](https://stripe.com/docs/payments/accept-a-payment).

### Optimizing performance

To improve your site's performance, you can hold off instantiating Stripe until the first render of your checkout page. To make sure that you don't reinstate Stripe on every render, we recommend that you use the singleton pattern to create/retrieve the Stripe instance:

```js
let stripePromise;
const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY);
  }
  return stripePromise;
};

const CheckoutPage = () => (
  <Elements stripe={getStripe()}>
    <CheckoutForm />
  </Elements>
);
```

### Defer loading Stripe.js

You can defer loading Stripe.js (lazy loading) until you call `loadStripe` by using the `/pure` import path:

```js
// Stripe.js will not be loaded until `loadStripe` is called
import { loadStripe } from '@stripe/stripe-js/pure';
```

Do note that this will cause Stripe to not collect any fraud signals on your page until `loadStripe` has been called, which can impact fraud detection performance.

### Disabling advanced fraud detection signals

If you would like to [disable advanced fraud detection](https://stripe.com/docs/disputes/prevention/advanced-fraud-detection#disabling-advanced-fraud-detection) altogether, use `loadStripe.setLoadParameters`:

```js
import { loadStripe } from '@stripe/stripe-js/pure';

loadStripe.setLoadParameters({ advancedFraudSignals: false });
const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
```

The `loadStripe.setLoadParameters` function is only available when importing `loadStripe` from `@stripe/stripe-js/pure`.

## React Hooks

In React, once you've loaded Stripe.js initially with `loadStripe` and passed it to the Elements component, you can use the `useStripe` hook throughout your child components to get a reference to the `stripe` object.

```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { loadStripe } from '@stripe/stripe-js';
import {
  CardElement,
  Elements,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';

const CheckoutForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: elements.getElement(CardElement),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit" disabled={!stripe}>
        Pay
      </button>
    </form>
  );
};

let stripePromise;
const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY);
  }
  return stripePromise;
};

const App = () => (
  <Elements stripe={getStripe()}>
    <CheckoutForm />
  </Elements>
);

ReactDOM.render(<App />, document.body);
```

## Examples

- [Next.js example CodeSandbox](https://codesandbox.io/s/github/stripe-samples/nextjs-typescript-react-stripe-js?file=/utils/get-stripejs.ts)
- [React example CodeSanbox](https://codesandbox.io/s/react-stripe-official-q1loc?fontsize=14&hidenavigation=1&theme=dark)
- [Parcel](https://github.com/stripe/stripe-js/tree/master/examples/parcel)
- [Rollup](https://github.com/stripe/stripe-js/tree/master/examples/rollup)
- [Webpack](https://github.com/stripe/stripe-js/tree/master/examples/webpack)

## Stripe.js Documentation

- [Stripe.js Docs](https://stripe.com/docs/stripe-js)
- [Stripe.js Reference](https://stripe.com/docs/api)
- [React Stripe.js Docs](https://stripe.com/docs/stripe-js/react)