Next.js + Stripe Checkout Integration How To

Next.js + Stripe Checkout Integration How To

Stripe integration isn’t exactly an everyday task kind of integration. It’s one of those things where when it works, it works and you just leave it until something needs to be done to it.

Every now and then I do a Stripe checkout integration. Every time, I find myself referring to the docs (which is fine).

However, it can feel like I’m waddling through documentation and trying to remember code snippets and whatever else.

This piece is a set of instructions that I wrote mostly for myself, with copy-paste code snippets to get Stripe working in Next.js. I’ve rearranged my notes and made them (hopefully) into a coherent tutorial.

I hope you like it 😁

Installing the Stripe npm package

To begin, you’ll need to install the stripe npm package in your Next.js project. You can do this by running the following command in your terminal:

npm install stripe

This will install the latest version of the Stripe npm package and add it to your project’s dependencies.

Setting up your Stripe account and retrieving your API keys

Before you can start using Stripe in your Next.js project, you’ll need to set up a Stripe account and retrieve your API keys. You can do this by following these steps:

  1. Go to the Stripe website (https://stripe.com/) and click on “Sign Up” in the top right corner.
  2. Follow the prompts to create a new Stripe account.
  3. Once your account is set up, click on the “Developers” tab in the top menu and then click on “API Keys” in the left-hand menu.
  4. Your API keys will be displayed on this page. Make sure to keep these keys safe, as they will be used to authenticate your Stripe API calls.

Adding your API keys to your Next.js project

Now that you have your API keys, you’ll need to add them to your Next.js project so that you can use them to make API calls to Stripe. There are a few different ways you can do this, but one common method is to add them as environment variables in your Next.js project.

To do this, you’ll need to create a .env file in the root directory of your Next.js project and add your API keys like this:

STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key
STRIPE_SECRET_KEY=sk_test_your_secret_key


Make sure to replace "your_publishable_key" and "your_secret_key" with the actual values of your API keys.

Using the stripe npm package in your Next.js project

Now that you have the stripe npm package installed and your API keys set up, you can start using the Stripe API in your Next.js project. Here’s an example of how you might use the stripe npm package to create a new customer:

import stripe from 'stripe';
 ​
 const stripe = new stripe(process.env.STRIPE_SECRET_KEY);
 ​
 async function createCustomer() {
   const customer = await stripe.customers.create({
     email: 'customer@example.com',
   });
   console.log(customer);
 }
 ​
 createCustomer();
 ​

This code will create a new customer with the email “customer@example.com” using the Stripe API. You can find more information on the different Stripe API methods and options in the Stripe documentation .

Getting Stripe’s checkout to work

Open the Next.js component where you want to use the Stripe Checkout library. At the top of the file, import the Stripe library by adding the following line:

import Stripe from 'stripe';

This will give you access to the Stripe object, which you can use to create a Stripe instance and interact with the Stripe API.

You can then use this instance to create a Stripe Checkout session, which is required to initiate a payment process using the Stripe Checkout library. To create a Stripe Checkout session, you will need to provide the following information:

  • The amount to be charged (in the smallest unit for the currency, e.g. cents for USD)
  • A description of the product or service being purchased
  • The currency in which the payment will be made
  • A success URL to which the user will be redirected after a successful payment
  • An optional cancel URL to which the user will be redirected if they cancel the payment process

Example Stripe Checkout session code:

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
 ​
 const session = await stripe.checkout.sessions.create({
   payment_method_types: ['card'],
   line_items: [
     {
       name: 'My Product',
       description: 'A description of my product',
       amount: 1000, // 10.00 USD in cents
       currency: 'usd',
       quantity: 1,
     },
   ],
   success_url: 'http://localhost:3000/success',
   cancel_url: 'http://localhost:3000/cancel',
 });
 ​

​Once you have created a Stripe Checkout session, you can use the session ID to initiate the payment process using the Stripe Checkout library. You can do this by adding a Stripe Checkout button to your component and setting the sessionId prop to the ID of the session you just created.

For example:

import StripeCheckout from 'react-stripe-checkout';
 ​
 <StripeCheckout
   stripeKey={process.env.STRIPE_PUBLISHABLE_KEY}
   sessionId={session.id}
   />

That’s it! Your Next.js component is now set up to use the Stripe Checkout library to accept payments from your customers.

Adding the Checkout script to your Next.js page

To add the Stripe Checkout script to your Next.js page, you will need to include the script in the head element of your page's HTML. This is a better way than just dropping in the script tag directly. You can do this by using the next/head component provided by Next.js.

First, import the Head component at the top of your page component:

import Head from 'next/head';

Then, use the Head component to add the Stripe Checkout script to the head element of your page:

<Head>
   <script src="https://js.stripe.com/v3/"></script>
 </Head>

​To add the Stripe Checkout script to your Next.js page, you will need to include the script in the head element of your page's HTML. You can do this by using the next/head component provided by Next.js.

First, import the Head component at the top of your page component:


 import Head from 'next/head';

Then, use the Head component to add the Stripe Checkout script to the head element of your page:

<Head>
   <script src="https://js.stripe.com/v3/"></script>
 </Head>

This will include the Stripe Checkout script on your page, allowing you to use the Stripe Checkout library to accept payments from your customers.

You will also need to include your Stripe publishable key in the script. You can do this by setting the stripeKey prop on the StripeCheckout component when you render it. The stripeKey prop should be set to your Stripe publishable key, which you can find in the Stripe dashboard.

For example:

import StripeCheckout from 'react-stripe-checkout';
 ​
 <StripeCheckout
   stripeKey={process.env.STRIPE_PUBLISHABLE_KEY}
   sessionId={session.id}
   />
 ​

Adding a button or a link that will trigger the Checkout process when clicked

To add a button that will trigger the Stripe Checkout process when clicked in a Next.js component, you will need to use the StripeCheckout component provided by the react-stripe-checkout library.

First, import the StripeCheckout component at the top of your component file:

import StripeCheckout from 'react-stripe-checkout';

Then, create a function that will be called when the button is clicked. This function will be responsible for initiating the Stripe Checkout process.

function handleCheckout() {
   // Initiate Stripe Checkout process here
 }

To initiate the Stripe Checkout process, you will need to set the sessionId prop on the StripeCheckout component to the ID of a Stripe Checkout session. You can create a Stripe Checkout session using the Stripe API as described in a previous section of this tutorial.

For example:

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
 ​
 async function handleCheckout() {
   const session = await stripe.checkout.sessions.create({
     payment_method_types: ['card'],
     line_items: [
       {
         name: 'My Product',
         description: 'A description of my product',
         amount: 1000, // 10.00 USD in cents
         currency: 'usd',
         quantity: 1,
       },
     ],
     success_url: 'http://localhost:3000/success',
     cancel_url: 'http://localhost:3000/cancel',
   });
 ​
   // Set the sessionId prop on the StripeCheckout component
   // to initiate the payment process
   setSessionId(session.id);
 }

Then, use the StripeCheckout component to render a button that will trigger the handleCheckout function when clicked. You will also need to set the stripeKey prop to your Stripe publishable key, which you can find in the Stripe dashboard. This will allow the Stripe Checkout library to authenticate your account and initiate the payment process.

For example:

import StripeCheckout from 'react-stripe-checkout';
 ​
 function MyComponent() {
   const [sessionId, setSessionId] = useState(null);
 ​
   return (
     <>
       <button onClick={handleCheckout}>Pay with Stripe</button>
       {sessionId && (
         <StripeCheckout
           stripeKey={process.env.STRIPE_PUBLISHABLE_KEY}
           sessionId={sessionId}
           />
       )}
     </>
   );
 }

That’s it!

Your button is now set up to trigger the Stripe Checkout process when clicked. Customers who click on the button will be redirected to the Stripe Checkout page, where they can enter their payment information and complete the payment.

💡
Want to sponsor matcha.fyi? You can have your brand featured right here. Let's connect and chat about it.