DEV Community

codeek
codeek

Posted on

💳 How to Implement Stripe Payments in an E-Commerce App: A Step-by-Step Guide with React & Express

Online payments are one of the most important parts of any modern e-commerce application. They are the bridge between a customer's cart and a successful order.

If you're building a shopping application and want to provide a secure, professional checkout experience, Stripe is one of the best payment platforms available.

In this guide, we'll build a Stripe Checkout integration using:

  • ⚛️ React + Vite
  • 🚀 Express.js
  • 💳 Stripe Checkout
  • 🌐 Axios

The implementation uses a hosted Stripe Checkout page, meaning Stripe securely handles all payment details while your application simply creates a checkout session.


Why Choose Stripe?

Stripe is trusted by thousands of businesses because it is:

  • ✅ Secure and reliable
  • ✅ Easy to integrate
  • ✅ PCI compliant
  • ✅ Supports multiple payment methods
  • ✅ Provides a beautiful hosted checkout experience

Instead of building your own payment form, Stripe redirects users to a secure hosted payment page, reducing both complexity and security concerns.


Step 1: Create a Stripe Account

Create a free Stripe account.

After logging into the Stripe Dashboard:

  1. Open Developers
  2. Navigate to API Keys
  3. Copy your Secret Key

⚠️ Important: Never expose your Stripe Secret Key in your frontend application. It should always remain on your backend.


Step 2: Install the Required Packages

Install the packages required for your Express backend.

npm install express stripe cors dotenv
Enter fullscreen mode Exit fullscreen mode

These packages help you:

  • Create the backend server
  • Connect with Stripe APIs
  • Handle CORS
  • Store sensitive keys securely

Step 3: Configure Environment Variables

Create a .env file inside your backend project.

STRIPE_SECRET_KEY=your_stripe_secret_key
PORT=5000
FRONTEND_URL=http://localhost:5173
Enter fullscreen mode Exit fullscreen mode

These variables allow your backend to:

  • Authenticate with Stripe
  • Run on the correct port
  • Redirect users back to your frontend after payment

Step 4: Create the Checkout Session (Backend)

Initialize Stripe inside your Express server.

import express from "express";
import Stripe from "stripe";
import cors from "cors";
import dotenv from "dotenv";

dotenv.config();

const app = express();

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

app.use(express.json());
app.use(cors());
Enter fullscreen mode Exit fullscreen mode

Now create a checkout session endpoint.

app.post("/create-checkout-session", async (req, res) => {
  try {
    const { cartItems } = req.body;

    const line_items = cartItems.map((item) => ({
      price_data: {
        currency: "usd",
        product_data: {
          name: item.title,
          images: [item.thumbnail],
        },
        unit_amount: Math.round(item.price * 100),
      },
      quantity: item.quantity,
    }));

    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      line_items,
      mode: "payment",
      success_url: `${process.env.FRONTEND_URL}/success`,
      cancel_url: `${process.env.FRONTEND_URL}/cart`,
    });

    res.json({
      url: session.url,
    });
  } catch (err) {
    console.error(err);

    res.status(500).json({
      error: "Something went wrong",
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

What happens here?

  • Receives cart items
  • Converts them into Stripe line items
  • Creates a Checkout Session
  • Returns the Stripe Checkout URL

This is the heart of the payment flow.


Step 5: Send Cart Data from React

When the customer clicks Checkout, send the cart items to your backend.

const res = await axios.post(
  `${apiBaseUrl}/create-checkout-session`,
  {
    cartItems,
  }
);

const { url } = res.data;

window.location.href = url;
Enter fullscreen mode Exit fullscreen mode

Payment Flow

User clicks Checkout
        │
        ▼
React sends cart to Express
        │
        ▼
Express creates Stripe Checkout Session
        │
        ▼
Stripe returns secure Checkout URL
        │
        ▼
Browser redirects to Stripe Checkout
Enter fullscreen mode Exit fullscreen mode

The payment form is fully hosted by Stripe.


Step 6: Configure Success & Cancel URLs

Inside your Checkout Session:

success_url: `${process.env.FRONTEND_URL}/success`,
cancel_url: `${process.env.FRONTEND_URL}/cart`,
Enter fullscreen mode Exit fullscreen mode

After payment:

  • ✅ Successful payments go to /success
  • ❌ Cancelled payments return users to /cart

You can use these pages to display an order confirmation or allow users to continue shopping.


Step 7: Test the Payment Flow

Before deploying to production, always test using Stripe Test Mode.

Use the following test card:

Field Value
Card Number 4242 4242 4242 4242
Expiry Any future date
CVC Any 3 digits

Verify that:

  • ✅ Checkout session is created
  • ✅ Payment succeeds
  • ✅ Redirect works correctly
  • ✅ Success page loads properly

Step 8: Production Improvements

Once everything works, consider adding:

  • 📦 Store orders in your database
  • 👤 Save customer information
  • 🚚 Store shipping details
  • 🔔 Handle Stripe Webhooks
  • 📄 Order history page
  • 💳 Multiple payment methods

Instead of generating order IDs with timestamps, use database-generated records for production applications.


Best Practices

Always remember to:

  • Never expose your Stripe Secret Key
  • Store sensitive values inside .env
  • Validate cart items on the backend
  • Handle API errors gracefully
  • Test thoroughly before production
  • Use Stripe Webhooks to confirm completed payments

Payment Flow Overview

User Adds Products
        │
        ▼
React Sends Cart
        │
        ▼
Express Backend
        │
        ▼
Stripe Checkout Session
        │
        ▼
Stripe Hosted Checkout
        │
        ▼
Payment Success
        │
        ▼
Success Page
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Adding Stripe transforms your application from a simple shopping website into a fully functional e-commerce platform.

By using a backend route to create Checkout Sessions and redirecting users to Stripe's hosted payment page, you can build a secure, scalable, and production-ready payment system with minimal effort.

If you're building a React + Express e-commerce project, this architecture is one of the simplest and most reliable approaches for accepting online payments.


🎥 Prefer Learning by Watching?

This article is based on the complete step-by-step video tutorial.

👉 Stripe Payment Integration Tutorial

https://www.youtube.com/watch?v=GjKbwPt9RlE&list=PL_02r0p8Ku_6tR8L-n-yj7MW8rrMtswwk&index=17

You'll learn how to:

  • Integrate Stripe Checkout
  • Build the backend payment API
  • Redirect users securely
  • Handle successful payments
  • Build a production-ready payment flow

🚀 Build a Complete Modern E-Commerce Application

If you're looking to master full-stack e-commerce development, check out the complete playlist where we build everything from scratch using modern technologies.

Topics Covered

  • ⚛️ React + Vite
  • 🎨 Chakra UI
  • 🛒 Shopping Cart
  • 🔄 React Query (TanStack Query)
  • 🌐 Axios
  • 📦 Zustand
  • 💳 Stripe Payment Integration
  • 🚀 Deployment
  • 📁 Clean Project Structure
  • 🔥 Best Practices

🎥 Complete E-Commerce Playlist

https://www.youtube.com/watch?v=Jluy-W9eP-4&list=PL_02r0p8Ku_6tR8L-n-yj7MW8rrMtswwk&index=1


If you enjoy practical, real-world React tutorials, consider following the series for more production-ready projects and modern development techniques.

Happy coding! 🚀

Top comments (0)