Importing Stripe.js as an ES Module

thorwebdev

Thor 闆风

Posted on March 26, 2020

Importing Stripe.js as an ES Module

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, 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 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:

npm install @stripe/stripe-js
# or
yarn add @stripe/stripe-js
Enter fullscreen mode Exit fullscreen mode

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.

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

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
Enter fullscreen mode Exit fullscreen mode

Replace the test API key above with your own publishable API key.

For more information on how to use Stripe.js once it loads, please refer to the Stripe.js API reference or follow the accept a payment guide.

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:

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

const CheckoutPage = () => (
  <Elements stripe={getStripe()}>
    <CheckoutForm />
  </Elements>
);
Enter fullscreen mode Exit fullscreen mode

Defer loading Stripe.js

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

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

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 altogether, use loadStripe.setLoadParameters:

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

loadStripe.setLoadParameters({ advancedFraudSignals: false });
const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
Enter fullscreen mode Exit fullscreen mode

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.

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);
Enter fullscreen mode Exit fullscreen mode

Examples

Stripe.js Documentation

馃挅 馃挭 馃檯 馃毄
thorwebdev
Thor 闆风

Posted on March 26, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related