paint-brush
Integrating Stripe Checkout with Next.js Is Easier Than You Thinkby@maksymmostovyi
109 reads New Story

Integrating Stripe Checkout with Next.js Is Easier Than You Think

by Maksym Mostovyi 5mFebruary 27th, 2025
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Want to accept payments in your Next.js app? This guide walks you through integrating Stripe Checkout step by step: ✅ Create a Stripe Account → Enable Test Mode and get API Keys ✅ Set Up Next.js → Install stripe and @stripe/stripe-js ✅ Backend: Create Checkout Session → Securely generate a session using Stripe API ✅ Frontend: Redirect to Checkout → Use redirectToCheckout(sessionId) for payments ✅ Test the Flow → Use Stripe Test Cards and ensure payments work 🎯 Result? A fully working payment system in your app, ready to go live when needed! 🚀

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Integrating Stripe Checkout with Next.js Is Easier Than You Think
Maksym Mostovyi  HackerNoon profile picture
0-item

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!

Why Use Stripe Checkout?

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

  1. Knowledge of how Stripe works under the hood

Step 1: Create a Stripe Account and Set Up Sandbox

Before diving into the code, you need to create a Stripe account and set up a Sandbox environment for testing.


  1. Create a Stripe Account
    • Go to the Stripe Dashboard and sign up or log in.
    • You’ll be redirected to the Stripe Dashboard.
  2. Switch to Test Mode
    • In the dashboard, toggle the switch for Test Mode (top right corner).
    • This allows you to simulate payments without real transactions.
  3. Get Your API Keys
    • Go to Developers → API Keys in the left sidebar.
    • Copy the following keys:
      • Publishable Key (pk_test_xxx) → Used on the frontend (safe to expose).
      • Secret Key (sk_test_xxx) → Used on the backend (keep it private!).
  4. Store Your API Keys Securely
    • 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!

Step 2: Set Up Next.js Project

  1. Create a New Next.js App

    create-next-app stripe-demo --typescript --tailwind
    cd stripe-demo
    
  2. 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 session

Step 3: Create a Checkout API Route

In 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');
  }
}

Step 4: Initialize Stripe in the Frontend

Create a utility file: utils/stripe.ts

import { loadStripe } from '@stripe/stripe-js';

export const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);


Step 5: Create a Checkout Button

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>
  );
}

Step 6: Test the Integration

  1. Start the development server
  2. Go to http://localhost:3000 and add items to the cart.
  3. Click Checkout → You’ll be redirected to Stripe’s secure checkout page.
  4. Complete the payment using Stripe’s test card numbers (e.g., 4242 4242 4242 4242).

Conclusion

🎉 Congratulations! You’ve successfully integrated Stripe Checkout into a Next.js app.
This guide showed you how to:


  • Create a Stripe account and use the Sandbox environment for testing.
  • Securely create Checkout sessions on the backend.
  • Redirect users to Stripe’s hosted checkout page.


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!