How to Create a Stripe Subscription with React and NextJS

Lonare
2 min readMar 9, 2023

--

(updated on 07 July 2023)

There are a lot of articles online demonstrating you how to create a stripe subscription with react and Next.js.

But they are either old or does not use the proper nomenclature to get this setup.

Hence, I created an article to step by step show you how you can create it without any mistake.

If you prefer to read the stripe documentation, here is the link.

Step 1: Set up your Stripe account and obtain API keys

Before you can start creating subscriptions, you’ll need to set up a Stripe account and obtain your API keys. You can sign up for a Stripe account for free and obtain your API keys from the dashboard.

Step 2: Install the Stripe library

To use Stripe with React and NextJS, you’ll need to install the Stripe library. You can do this by running the following command in your terminal:

npm install stripe

Step 3: Create a ui for User

Create a UI for custimer where user can select a price_id which you have created in previous step on stripe dashboar.

Step 4: Create a Stripe instance

Next, create a stripe instance for creating a subscription

async function create_subscription(){
try {
// Create Checkout Sessions from body params.
const session = await stripe.checkout.sessions.create({
line_items: [
{
// Provide the exact Price ID (for example, pr_1234) of the product you want to sell
price: 'price_Id',
quantity: 1,
},
],
mode: 'subscription',
success_url: `http://localhost:3000/groups/create/plan?success=true`,
cancel_url: `http://localhost:3000/groups/create/plan?canceled=true`,
});
console.log(session.url);
setRedirect(session.url);

} catch (err) {
console.log(err);
}
}

Step 5: Capture the checkout url into a State

Now capture the state url into a state and then crete a function to redirect to stripe:

const router = useRouter();
const [redirect, setRedirect] = useState();

function process(){
router.push(redirect);
}

Step 6: Create a button to initiate the redirect

Create a button to initiate the redirect. You can also redirect from a server component but for that you need express or http. I found it easy this way.

return (
<>
<h1> here </h1>
<a onClick={() => process()}>do it</a>
</>
);

Tip 1# Install Stripe Extension on your VS Code for testing

Tip 2# Install Stipe CLI on your machine

--

--

Lonare
Lonare

Written by Lonare

Imagination is the key to unlock the world. I am trying to unlock mine.

No responses yet