Next.js course Β· Module 9: Integrations and Advanced Features

Next.js and Stripe - A Complete Payment System

10 min read Β·
In this lesson9

In the futuristic Quantum Metropolis, where transactions happen instantly and securely, you will learn about integrating Next.js with Stripe - the most popular online payment platform. This combination allows you to build professional e-commerce systems with full payment support.

What is Stripe?

Stripe is a comprehensive online payment platform that offers:

  • Global payments - support for 135+ currencies and payment methods
  • Developer-friendly API - clear documentation and SDKs
  • Security - PCI DSS Level 1 compliance
  • Subscription management - subscription handling
  • Fraud prevention - advanced protection against fraud
  • Webhooks - real-time notifications about events

Installation and configuration

Step 1: Creating a Stripe account

  1. Sign up at stripe.com
  2. Go to Dashboard β†’ Developers β†’ API keys
  3. Copy the keys:
    • Publishable key - used on the client side
    • Secret key - used only on the server side

Step 2: Package installation

# Install the Stripe SDK
npm install stripe @stripe/stripe-js @stripe/react-stripe-js

# For TypeScript, add the types
npm install -D @types/stripe

Step 3: Environment variables configuration

Create the file .env.local:

# Stripe keys
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# App URL
NEXT_PUBLIC_APP_URL=http://localhost:3000

Basic integration

Step 1: Initializing Stripe

Create a Stripe instance on the server side:

// lib/stripe.ts
import Stripe from 'stripe';

if (!process.env.STRIPE_SECRET_KEY) {
  throw new Error('STRIPE_SECRET_KEY is not defined');
}

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2023-10-16',
  typescript: true,
});

On the client side:

// lib/stripe-client.ts
import { loadStripe } from '@stripe/stripe-js';

if (!process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) {
  throw new Error('NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY is not defined');
}

// Singleton pattern for better performance
let stripePromise: Promise<any>;

export const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
  }
  return stripePromise;
};

Step 2: Stripe Provider

Wrap the application in Stripe Provider:

// app/providers.tsx
'use client';

import { Elements } from '@stripe/react-stripe-js';
import { getStripe } from '@/lib/stripe-client';

interface ProvidersProps {
  children: React.ReactNode;
}

export function Providers({ children }: ProvidersProps) {
  return (
    <Elements stripe={getStripe()}>
      {children}
    </Elements>
  );
}

// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        <Providers>
          {children}
        </Providers>
      </body>
    </html>
  );
}

Payment implementation

Stripe Checkout is a ready-made, hosted payment form:

// app/api/checkout/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';

export async function POST(request: NextRequest) {
  try {
    const { items } = await request.json();

    // Validation items
    if (!items || !Array.isArray(items) || items.length === 0) {
      return NextResponse.json(
        { error: 'No items provided' },
        { status: 400 }
      );
    }

    // Creating line items for Stripe
    const lineItems = items.map(item => ({
      price_data: {
        currency: 'pln',
        product_data: {
          name: item.name,
          description: item.description,
          images: item.images ? [item.images] : [],
        },
        unit_amount: Math.round(item.price * 100), // Stripe uses cents
      },
      quantity: item.quantity,
    }));

    // Creating the checkout session
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card', 'blik', 'p24'],
      line_items: lineItems,
      mode: 'payment',
      success_url: `${process.env.NEXT_PUBLIC_APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/cart`,
      metadata: {
        orderId: 'unique-order-id',
        customerId: 'customer-id',
      },
      locale: 'pl',
    });

    return NextResponse.json({ sessionId: session.id });
  } catch (error) {
    console.error('Checkout error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

Component for handling checkout:

// components/CheckoutButton.tsx
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { getStripe } from '@/lib/stripe-client';

interface CheckoutButtonProps {
  items: Array<{
    name: string;
    description?: string;
    price: number;
    quantity: number;
    images?: string;
  }>;
}

export function CheckoutButton({ items }: CheckoutButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const handleCheckout = async () => {
    setLoading(true);

    try {
      // Creating the checkout session
      const response = await fetch('/api/checkout', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ items }),
      });

      const { sessionId, error } = await response.json();

      if (error) {
        throw new Error(error);
      }

      // Redirect to Stripe Checkout
      const stripe = await getStripe();
      const { error: stripeError } = await stripe!.redirectToCheckout({
        sessionId,
      });

      if (stripeError) {
        throw stripeError;
      }
    } catch (error) {
      console.error('Checkout error:', error);
      alert('An error occurred during redirect to payment');
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={handleCheckout}
      disabled={loading}
      className="bg-blue-600 text-white px-6 py-3 rounded-lg disabled:opacity-50"
    >
      {loading ? 'Redirecting...' : 'Go to payment'}
    </button>
  );
}

Payment Element (Custom Form)

For greater UX control, use Payment Element:

// components/PaymentForm.tsx
'use client';

import { useState, FormEvent } from 'react';
import {
  PaymentElement,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';

interface PaymentFormProps {
  clientSecret: string;
}

export function PaymentForm({ clientSecret }: PaymentFormProps) {
  const stripe = useStripe();
  const elements = useElements();
  const [error, setError] = useState<string | null>(null);
  const [processing, setProcessing] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setProcessing(true);
    setError(null);

    const { error: submitError } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: `${window.location.origin}/payment-success`,
      },
    });

    if (submitError) {
      setError(submitError.message || 'An error occurred');
      setProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <PaymentElement
        options={{
          layout: 'tabs',
          paymentMethodOrder: ['card', 'blik', 'p24'],
        }}
      />

      {error && (
        <div className="text-red-600 text-sm">{error}</div>
      )}

      <button
        type="submit"
        disabled={!stripe || processing}
        className="w-full bg-blue-600 text-white py-3 rounded-lg disabled:opacity-50"
      >
        {processing ? 'Processing...' : 'Pay'}
      </button>
    </form>
  );
}

Payment Intent API

// app/api/payment-intent/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';

export async function POST(request: NextRequest) {
  try {
    const { amount, currency = 'pln' } = await request.json();

    // Validate the amount
    if (!amount || amount <= 0) {
      return NextResponse.json(
        { error: 'Invalid amount' },
        { status: 400 }
      );
    }

    // Creating the Payment Intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Conversion to grosze (1/100 PLN)
      currency,
      automatic_payment_methods: {
        enabled: true,
      },
      metadata: {
        orderId: 'unique-order-id',
      },
    });

    return NextResponse.json({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (error) {
    console.error('Payment intent error:', error);
    return NextResponse.json(
      { error: 'Failed to create payment intent' },
      { status: 500 }
    );
  }
}

Webhooks

Webhooks allow you to receive notifications about events in Stripe:

// app/api/webhooks/stripe/route.ts
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import Stripe from 'stripe';

export async function POST(request: NextRequest) {
  const body = await request.text();
  const signature = (await headers()).get('stripe-signature');

  if (!signature) {
    return NextResponse.json(
      { error: 'Missing stripe-signature header' },
      { status: 400 }
    );
  }

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (error) {
    console.error('Webhook signature verification failed:', error);
    return NextResponse.json(
      { error: 'Invalid signature' },
      { status: 400 }
    );
  }

  // Handle different event types
  try {
    switch (event.type) {
      case 'checkout.session.completed': {
        const session = event.data.object as Stripe.Checkout.Session;

        // Handle completed payment
        await handleSuccessfulPayment(session);
        break;
      }

      case 'payment_intent.succeeded': {
        const paymentIntent = event.data.object as Stripe.PaymentIntent;

        // Update order status
        console.log('Payment succeeded:', paymentIntent.id);
        break;
      }

      case 'payment_intent.payment_failed': {
        const paymentIntent = event.data.object as Stripe.PaymentIntent;

        // Handle failed payment
        console.log('Payment failed:', paymentIntent.id);
        break;
      }

      case 'customer.subscription.created':
      case 'customer.subscription.updated':
      case 'customer.subscription.deleted': {
        const subscription = event.data.object as Stripe.Subscription;

        // Handle subscription changes
        await handleSubscriptionChange(subscription);
        break;
      }

      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    return NextResponse.json({ received: true });
  } catch (error) {
    console.error('Webhook handler error:', error);
    return NextResponse.json(
      { error: 'Webhook handler failed' },
      { status: 500 }
    );
  }
}

async function handleSuccessfulPayment(session: Stripe.Checkout.Session) {
  // Implement logic after successful payment
  console.log('Payment successful for session:', session.id);

  // Example: Update order status in the database
  // await updateOrderStatus(session.metadata.orderId, 'paid');

  // Send confirmation email
  // await sendConfirmationEmail(session.customer_email);
}

async function handleSubscriptionChange(subscription: Stripe.Subscription) {
  // Implement the subscription logic
  console.log('Subscription changed:', subscription.id);
}

Subscriptions

Implementing a subscription system:

// app/api/subscription/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { auth } from '@/lib/auth'; // Your authentication function

export async function POST(request: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { priceId } = await request.json();

    // Find or create customer in Stripe
    let customerId: string;

    const customers = await stripe.customers.list({
      email: session.user.email,
      limit: 1,
    });

    if (customers.data.length > 0) {
      customerId = customers.data[0].id;
    } else {
      const customer = await stripe.customers.create({
        email: session.user.email,
        metadata: {
          userId: session.user.id,
        },
      });
      customerId = customer.id;
    }

    // Create checkout session for subscription
    const checkoutSession = await stripe.checkout.sessions.create({
      customer: customerId,
      payment_method_types: ['card'],
      line_items: [
        {
          price: priceId,
          quantity: 1,
        },
      ],
      mode: 'subscription',
      allow_promotion_codes: true,
      success_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
      metadata: {
        userId: session.user.id,
      },
    });

    return NextResponse.json({ sessionId: checkoutSession.id });
  } catch (error) {
    console.error('Subscription error:', error);
    return NextResponse.json(
      { error: 'Failed to create subscription' },
      { status: 500 }
    );
  }
}

Customer Portal

Allow users to manage subscriptions:

// app/api/customer-portal/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { auth } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Find customer
    const customers = await stripe.customers.list({
      email: session.user.email,
      limit: 1,
    });

    if (customers.data.length === 0) {
      return NextResponse.json(
        { error: 'Customer not found' },
        { status: 404 }
      );
    }

    // Create Customer Portal session
    const portalSession = await stripe.billingPortal.sessions.create({
      customer: customers.data[0].id,
      return_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`,
    });

    return NextResponse.json({ url: portalSession.url });
  } catch (error) {
    console.error('Customer portal error:', error);
    return NextResponse.json(
      { error: 'Failed to create portal session' },
      { status: 500 }
    );
  }
}

Security

1. Server-side validation

Always validate data on the server side:

// lib/validation.ts
import { z } from 'zod';

export const checkoutSchema = z.object({
  items: z.array(z.object({
    name: z.string().min(1).max(100),
    description: z.string().optional(),
    price: z.number().positive(),
    quantity: z.number().int().positive(),
    images: z.string().url().optional(),
  })).min(1),
});

// Usage in API route
const validatedData = checkoutSchema.parse(await request.json());

2. Rate limiting

Protect the API against abuse:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, '10 s'),
});

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/api/')) {
    const ip = request.ip ?? '127.0.0.1';
    const { success } = await ratelimit.limit(ip);

    if (!success) {
      return NextResponse.json(
        { error: 'Too many requests' },
        { status: 429 }
      );
    }
  }

  return NextResponse.next();
}

3. Webhook security

Always verify webhook signatures:

// Use stripe.webhooks.constructEvent() as shown earlier
// Additionally, you can add IP whitelisting
const allowedIPs = [
  '3.18.12.63',
  '3.130.192.231',
  // Full list: https://stripe.com/docs/ips
];

Testing

Test mode

Stripe offers a test mode with test cards:

// Popular test cards
const testCards = {
  success: '4242424242424242',
  decline: '4000000000000002',
  authRequired: '4000002500003155',
  insufficientFunds: '4000000000009995',
};

Testing webhooks locally

Use Stripe CLI:

# Installation
brew install stripe/stripe-cli/stripe

# Log in
stripe login

# Forward webhooks to the local server
stripe listen --forward-to localhost:3000/api/webhooks/stripe

# Test webhook
stripe trigger payment_intent.succeeded

Summary

Integrating Next.js with Stripe provides powerful capabilities for building payment systems. Key elements include:

  1. Checkout Session - for quick implementation
  2. Payment Element - for custom UX
  3. Webhooks - for reliability
  4. Security - validation and rate limiting
  5. Testing - test mode and Stripe CLI

This combination allows you to build professional e-commerce applications, SaaS with subscriptions, marketplaces, and more.

Code for this lesson: App.tsx
import React, { useState } from 'react';

interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  image: string;
}

interface CartItem extends Product {
  quantity: number;
}

const products: Product[] = [
  { id: 'prod_1', name: 'Quantum Shield Pro', description: 'Advanced data protection', price: 4999, image: '' },
  { id: 'prod_2', name: 'Neural Interface v3', description: 'AI programming interface', price: 9999, image: '' },
  { id: 'prod_3', name: 'Cyber Toolkit', description: 'Developer toolkit', price: 2499, image: '' },
  { id: 'prod_4', name: 'Data Stream Engine', description: 'Data processing engine', price: 7499, image: '' },
];

const StripeDemo = () => {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [step, setStep] = useState<'shop' | 'checkout' | 'success'>('shop');
  const [processing, setProcessing] = useState(false);
  const [logs, setLogs] = useState<string[]>([]);

  const addToCart = (product: Product) => {
    setCart(prev => {
      const existing = prev.find(i => i.id === product.id);
      if (existing) return prev.map(i => i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i);
      return [...prev, { ...product, quantity: 1 }];
    });
  };

  const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);

  const handleCheckout = async () => {
    setProcessing(true);
    setLogs([]);
    const addLog = (msg: string) => setLogs(prev => [...prev, msg]);

    addLog('POST /api/checkout - Creating Stripe session...');
    await new Promise(r => setTimeout(r, 500));
    addLog('stripe.checkout.sessions.create({ mode: "payment" })');
    await new Promise(r => setTimeout(r, 400));
    addLog('Session created: cs_live_a1B2c3D4...');
    await new Promise(r => setTimeout(r, 300));
    addLog('Redirecting to Stripe Checkout...');
    await new Promise(r => setTimeout(r, 600));
    addLog('Payment successful! session.payment_status: "paid"');
    await new Promise(r => setTimeout(r, 300));
    addLog('Webhook received: checkout.session.completed');
    addLog('Order fulfilled. Redirecting to success page...');
    await new Promise(r => setTimeout(r, 400));

    setStep('success');
    setProcessing(false);
  };

  const formatPrice = (cents: number) => (cents / 100).toFixed(2) + ' CR';

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
      <h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + Stripe Payments</h1>

      {step === 'shop' && (
        <div style={{ maxWidth: '800px', margin: '20px auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '20px' }}>
            {products.map(p => (
              <div key={p.id} style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '10px', border: '1px solid #333' }}>
                <div style={{ fontSize: '48px', textAlign: 'center' }}>{p.image}</div>
                <h3 style={{ color: '#64ffda', margin: '8px 0' }}>{p.name}</h3>
                <p style={{ color: '#888', fontSize: '13px' }}>{p.description}</p>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '12px' }}>
                  <span style={{ color: '#7c4dff', fontWeight: 'bold' }}>{formatPrice(p.price)}</span>
                  <button onClick={() => addToCart(p)} style={{ padding: '8px 16px', background: '#7c4dff', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
                    Add to Cart
                  </button>
                </div>
              </div>
            ))}
          </div>
          {cart.length > 0 && (
            <div style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '10px', border: '1px solid #7c4dff' }}>
              <h3 style={{ color: '#64ffda' }}>Cart ({cart.reduce((s, i) => s + i.quantity, 0)})</h3>
              {cart.map(item => (
                <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #222' }}>
                  <span>{item.image} {item.name} x{item.quantity}</span>
                  <span style={{ color: '#7c4dff' }}>{formatPrice(item.price * item.quantity)}</span>
                </div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '12px', paddingTop: '12px', borderTop: '2px solid #7c4dff' }}>
                <strong>Total:</strong>
                <strong style={{ color: '#64ffda' }}>{formatPrice(total)}</strong>
              </div>
              <button onClick={() => setStep('checkout')} style={{ width: '100%', marginTop: '12px', padding: '12px', background: 'linear-gradient(45deg, #7c4dff, #64ffda)', border: 'none', borderRadius: '8px', color: '#0f0f23', fontWeight: 'bold', cursor: 'pointer', fontSize: '16px' }}>
                Proceed to Payment
              </button>
            </div>
          )}
        </div>
      )}

      {step === 'checkout' && (
        <div style={{ maxWidth: '600px', margin: '20px auto' }}>
          <div style={{ background: 'rgba(255,255,255,0.05)', padding: '24px', borderRadius: '10px', border: '1px solid #333' }}>
            <h2 style={{ color: '#64ffda', marginBottom: '16px' }}>Stripe Checkout</h2>
            <p style={{ color: '#888', marginBottom: '16px' }}>Total: <strong style={{ color: '#7c4dff' }}>{formatPrice(total)}</strong></p>
            <button onClick={handleCheckout} disabled={processing}
              style={{ width: '100%', padding: '14px', background: processing ? '#555' : '#635bff', border: 'none', borderRadius: '8px', color: '#fff', fontWeight: 'bold', cursor: processing ? 'default' : 'pointer', fontSize: '16px' }}>
              {processing ? 'Processing...' : 'Pay with Stripe'}
            </button>
          </div>
          {logs.length > 0 && (
            <div style={{ background: '#000', padding: '16px', borderRadius: '10px', marginTop: '16px', fontFamily: 'monospace', fontSize: '12px' }}>
              {logs.map((log, i) => (<div key={i} style={{ color: '#0f0', padding: '2px 0' }}>{log}</div>))}
            </div>
          )}
        </div>
      )}

      {step === 'success' && (
        <div style={{ maxWidth: '500px', margin: '40px auto', textAlign: 'center' }}>
          <div style={{ fontSize: '64px' }}>OK</div>
          <h2 style={{ color: '#64ffda', margin: '16px 0' }}>Payment Complete!</h2>
          <p style={{ color: '#888' }}>Order has been processed successfully.</p>
          <button onClick={() => { setStep('shop'); setCart([]); setLogs([]); }}
            style={{ marginTop: '20px', padding: '12px 24px', background: '#7c4dff', border: 'none', borderRadius: '8px', color: '#fff', cursor: 'pointer' }}>
            Back to Shop
          </button>
        </div>
      )}
    </div>
  );
};

export default StripeDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Stripe Checkout Session requires:

  2. 2. What is the relationship between Product and Price in Stripe?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Implement the payment process with Stripe Checkout in a Next.js application

  • Click in order

    Arrange the steps of handling Stripe webhooks in order.

  • Code editor

    Create an API route for Checkout Session.

  1. QuestionStripe Checkout Session
  2. QuestionStripe Products and Prices
  3. Coding taskPractice: Stripe Checkout in Next.js
  4. Click in orderStripe Webhooks
  5. Coding taskStripe Checkout Integration
  6. QuestionSubscriptions in Stripe

Useful articles