
Integrating payments into your web app might sound complicated, but with Stripe Checkout and Next.js, it’s easier than you think! In this guide, I’ll show you how to set up Stripe Checkout step by step, so you can start accepting payments with minimal hassle.
Whether you're building an e-commerce store, a SaaS product, or any app that needs payments, this tutorial covers everything from setting up a Stripe account to handling payment redirects securely. Let’s get started!
Stripe Checkout provides a secure and customizable payment flow that’s perfect for any web app. It’s PCI-compliant, easy to integrate, and supports a wide variety of payment methods like credit cards, Apple Pay, and Google Pay. By the end of this guide, you’ll have:
1. A workingNext.js app with Stripe Checkoutintegrated
2. Securepayment processing with Stripe
Before diving into the code, you need to create a Stripe account and set up a Sandbox environment for testing.
pk_test_xxx
) → Used on the frontend (safe to expose).sk_test_xxx
) → Used on the backend (keep it private!).In your Next.js project, create a .env.local
file and add:
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
NEXT_PUBLIC_BASE_URL=http://localhost:3000
Important: Never expose your Secret Key in frontend code!
Create a New Next.js App
create-next-app stripe-demo --typescript --tailwind
cd stripe-demo
Install Dependencies
npm install stripe @stripe/stripe-js
@stripe/stripe-js
: Used on the frontend to redirect to Checkout.stripe
: Used on the backend to create a Checkout sessionIn Next.js, API routes are created in the pages/api
folder. We’ll use this to securely create a Checkout Session on the server side.
Create a file: pages/api/create-checkout-session.ts
import Stripe from 'stripe';
import { NextApiRequest, NextApiResponse } from 'next';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
apiVersion: '2023-10-16',
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
try {
const { items } = req.body;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: items.map((item: any) => ({
price_data: {
currency: 'usd',
product_data: { name: item.name },
unit_amount: item.price * 100,
},
quantity: item.quantity,
})),
mode: 'payment',
success_url: `${process.env.NEXT_PUBLIC_BASE_URL}/success`,
cancel_url: `${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,
});
res.status(200).json({ sessionId: session.id });
} catch (err) {
res.status(500).json({ error: 'Error creating checkout session' });
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
}
Create a utility file: utils/stripe.ts
import { loadStripe } from '@stripe/stripe-js';
export const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
Modify pages/index.tsx
to add a simple product list and a checkout button.
import { useState } from 'react';
import { stripePromise } from '../utils/stripe';
const products = [
{ id: '1', name: 'Product 1', price: 1000 },
{ id: '2', name: 'Product 2', price: 2000 },
];
export default function Home() {
const [cart, setCart] = useState(products);
const handleCheckout = async () => {
const stripe = await stripePromise;
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: cart }),
});
const { sessionId } = await response.json();
stripe?.redirectToCheckout({ sessionId });
};
return (
<div>
<h1>Products</h1>
{cart.map((item) => (
<div key={item.id}>
<p>{item.name} - ${item.price / 100}</p>
</div>
))}
<button onClick={handleCheckout}>Checkout</button>
</div>
);
}
http://localhost:3000
and add items to the cart.4242 4242 4242 4242
).🎉 Congratulations! You’ve successfully integrated Stripe Checkout into a Next.js app.
This guide showed you how to:
With this setup, you can start accepting payments safely and efficiently. 🚀 If you would like to watch that tutorial in video format please welcome to my youtube channel MaksDevInsights. I hope to see you there. Cheers!