DEV Community

codeek
codeek

Posted on • Edited 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)