Create a Stripe subscription with ReactJS and NodeJS (Step by Step)
To create a Stripe subscription with ReactJS and NodeJS, you will need to:
- Install the Stripe SDKs for React and NodeJS:
npm install @stripe/stripe-js @stripe/react-stripe-js
- Initialize the Stripe SDK in your NodeJS backend:
const stripe = require('stripe');
stripe.setApiKey('YOUR_STRIPE_SECRET_KEY');- Create a route in your NodeJS backend to create a subscription:
app.post('/create-subscription', async (req, res) => {
const { priceId, customer } = req.body;
const subscription = await stripe.subscriptions.create({
customer,
items: [{ price: priceId }],
});
res.send(subscription);
});- Create a React component to render a subscription form:
import React, { useState } from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import CardElement from '@stripe/react-stripe-js/CardElement';
const stripePromise = loadStripe('YOUR_STRIPE_PUBLISHABLE_KEY');
const SubscriptionForm = () => {
const [priceId, setPriceId] = useState(null);
const [customer, setCustomer] = useState(null);
const [cardElement, setCardElement] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
const stripe = await stripePromise;
const paymentMethod = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});
const subscription = await fetch('/create-subscription', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
priceId,
customer,
paymentMethod,
}),
});
const subscriptionData = await subscription.json();
// Handle the subscription data here
};
return (
<Elements stripe={stripePromise}>
<form onSubmit={handleSubmit}>
<select value={priceId} onChange={(event) => setPriceId(event.target.value)}>
<option value="price_1234567890">Monthly Plan</option>
<option value="price_9876543210">Yearly Plan</option>
</select>
<CardElement ref={setCardElement} />
<button type="submit">Subscribe</button>
</form>
</Elements>
);
};
export default SubscriptionForm;- Use the
SubscriptionFormcomponent in your React app to allow users to subscribe to your plans.
Once you have completed these steps, you will be able to create Stripe subscriptions with ReactJS and NodeJS.





