Stripe Integration in Next.js

12. April, 2025 3 min read Develop

Seamless Payments with Stripe and Next.js

Integrating a robust payment system is crucial for modern web applications. Stripe, combined with Next.js, offers a powerful solution for handling payments efficiently and securely.

In this guide, we’ll walk through integrating Stripe into a Next.js application, covering setup, implementation, and best practices to ensure a smooth payment experience for your users.

Why Choose Stripe?

Stripe is a leading payment processing platform known for its:

  • Developer-Friendly APIs: Easy-to-use APIs that simplify payment integration.
  • Security: PCI-compliant and equipped with advanced fraud detection.
  • Global Reach: Supports multiple currencies and payment methods.
  • Customizable Checkout: Offers both pre-built and customizable checkout experiences.

Setting Up Stripe in Next.js

1. Install Dependencies

Begin by installing the necessary packages:

npm install stripe @stripe/stripe-js
  • stripe: Server-side SDK for interacting with Stripe’s API.
  • @stripe/stripe-js: Client-side library for Stripe.js.

2. Configure Environment Variables

Create a .env.local file in your project’s root directory and add your Stripe keys:

NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_XXXXXXXXXXXXXXXXXXXXXXXX
STRIPE_SECRET_KEY=sk_test_XXXXXXXXXXXXXXXXXXXXXXXX

Ensure these keys are kept secure and not exposed publicly.

3. Create a Checkout Session API Route

Set up an API route to create a Stripe Checkout session:

// pages/api/create-checkout-session.js
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
          {
            price_data: {
              currency: 'usd',
              product_data: {
                name: 'Sample Product',
              },
              unit_amount: 2000,
            },
            quantity: 1,
          },
        ],
        mode: 'payment',
        success_url: `${req.headers.origin}/success`,
        cancel_url: `${req.headers.origin}/cancel`,
      });

      res.status(200).json({ id: session.id });
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

4. Implement the Checkout Button on the Client

Create a checkout button that initiates the payment process:

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

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

export default function CheckoutButton() {
  const handleClick = async () => {
    const stripe = await stripePromise;
    const response = await fetch('/api/create-checkout-session', {
      method: 'POST',
    });
    const session = await response.json();
    const result = await stripe.redirectToCheckout({
      sessionId: session.id,
    });

    if (result.error) {
      console.error(result.error.message);
    }
  };

  return (
    <button role="link" onClick={handleClick}>
      Checkout
    </button>
  );
}

Include this component in your page to provide a checkout option to users.

Testing the Integration

Stripe provides test card numbers to simulate transactions. For example:

  • Card Number: 4242 4242 4242 4242
  • Expiry Date: Any future date
  • CVC: Any 3-digit number

Use these details to test the payment flow without real transactions.

Best Practices

  • Secure API Keys: Never expose your secret keys on the client side.
  • Handle Webhooks: Set up Stripe webhooks to handle events like payment success or failure.
  • Validate Inputs: Ensure all user inputs are validated to prevent errors.
  • Error Handling: Implement comprehensive error handling for a smooth user experience.

Conclusion

Integrating Stripe into your Next.js application streamlines the payment process, offering a secure and user-friendly experience. By following the steps outlined above, you can set up a robust payment system tailored to your application’s needs.

‘Till next time!