Youll now be able to reach the Stripe account using the API keys.

Installing the Stripe npm Package

Run this command to set up the Stripe npm package.

Import the Stripe library into your checkout component page.

Person holding debit card

In the API folder, create a new file called checkout-session.js file.

Initialize the Stripe object with the API keys you retrieved from your Stripe dashboard.

In the handler function, get the items to check out from the body parameters.

Create a checkout session object to the handler function and pass the items.

Check out this post oncreating API routes in Next.jsfor a more in-depth explanation of Next.js API routes.

@stripe/stripe-js library is a loading utility thatll help you load the Stripe.js instance.

Once the installation finishes, create a new file in your /components directory named /components/checkout.js.

Then call the loadstripe function from @stripe/stripe-js library, passing the publishable key as an argument.

loadstripe() returns a promise that resolves with a newly created Stripe object once Stripe.js has loaded.

Next, add a function to create a checkout session in the component.

This function usesAxios to call the APIyou created in the /api folder to retrieve the checkout session.

Add a checkout button in the return statement thatll trigger the handleCheckout function when clicked.

you’ve got the option to call the checkout component on the cart page.

The cancel URL maps to the /cancel route, while the success URL maps to the /success route.

Add two components in the /pages folder named success and cancel to handle these URLs.

In pages/success.js, add the success component.

In pages/cancel.js, add the cancel component.

Now, Stripe will redirect to either of these pages depending on the checkout status.

All these options allow you to customize the checkout process to suit your system.

Why Use Stripe for the Checkout Page?

Stripe checkout helps you reduce development time, allowing you to start accepting payments within a short time.