DEV Community

Ahmad Tibibi
Ahmad Tibibi

Posted on

Stripe with Next.js

Integrating Stripe with Next.js: A Comprehensive Guide

What is Next.js?

Next.js is a powerful React framework that allows developers to build server-rendered and statically generated applications easily. It adds essential features like file-based routing, automatic code splitting, and server-side rendering (SSR) to React. This means that developers can create fast, highly optimized applications without having to manage all the configurations typically associated with a React app.

What is a Framework?

A framework is a set of tools, libraries, and best practices that streamlines the development process. Rather than starting from scratch, developers can build on top of the framework, which provides built-in functions and structures. This saves time and allows for consistent coding practices across a project.

Why Integrate Stripe with Next.js?

Stripe is a popular payment processing platform that enables businesses to accept online payments securely. Integrating Stripe with Next.js combines the strengths of both: Next.js provides a robust framework for building user interfaces, while Stripe handles the complexities of online transactions.

The integration of Stripe with Next.js is necessary for e-commerce applications that require quick and efficient payment processing. By using the two together, developers can create a seamless user experience for payment processing, manage subscriptions, and handle other payment-related functionalities efficiently.

Setting Up Stripe with Next.js

To integrate Stripe with Next.js, you need some prerequisites and basic knowledge:

Prerequisites

  • Basic understanding of JavaScript and React: Familiarity with these technologies is crucial as Next.js is built on top of React.
  • Knowledge of TypeScript: Since this article emphasizes TypeScript usage, understanding its syntax and how it enhances JavaScript with static typing is important.
  • Stripe Account: You will need a Stripe account to access their API keys for payment processing.

Important Things to Know

  1. Environment Variables: Always store sensitive information like API keys as environment variables.
  2. Secure your API routes: Ensure that your Next.js API routes are secure, especially when dealing with payment processing.

Installation

Here's how to get started with Stripe in your Next.js application:

Install the required packages:

npm install stripe @stripe/react-stripe-js
Enter fullscreen mode Exit fullscreen mode

Creating Payment Functionality with Stripe in Next.js

Step 1: Configure the Stripe Client

Create a new file lib/stripe.ts to initialize Stripe with your secret key:

import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
    apiVersion: '2022-11-15',
});

export default stripe;
Enter fullscreen mode Exit fullscreen mode

Step 2: Create an API Route for Payments

Create an API route to handle payment processing. Inside the pages/api directory, create a file called checkout.ts:

import type { NextApiRequest, NextApiResponse } from 'next';
import stripe from '../../lib/stripe';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method === 'POST') {
        const { items } = req.body;

        // Create a new Checkout Session
        const session = await stripe.checkout.sessions.create({
            line_items: items.map((item: { id: string; quantity: number }) => ({
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: item.id,
                    },
                    unit_amount: item.amount,
                },
                quantity: item.quantity,
            })),
            mode: 'payment',
            success_url: `${process.env.NEXT_PUBLIC_URL}/success`,
            cancel_url: `${process.env.NEXT_PUBLIC_URL}/cancel`,
        });

        res.status(200).json({ id: session.id });
    } else {
        res.setHeader('Allow', ['POST']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Frontend Implementation

In the frontend, use Stripe's React components to create a payment button. For this, let’s modify a component:

import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js';

const CheckoutForm = () => {
    const stripe = useStripe();
    const elements = useElements();

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

        const { error, paymentIntent } = await stripe?.confirmCardPayment(/* clientSecret here */);

        if (error) {
            console.error(error);
        } else {
            console.log('Payment Successful!', paymentIntent);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <CardElement />
            <button type="submit" disabled={!stripe}>Pay</button>
        </form>
    );
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)