Back to articles

Building a Serverless E-commerce Store with React & Stripe Functions

AuthorMajd Muhtaseb06/15/20258 minutes
Building a Serverless E-commerce Store with React & Stripe Functions

Introduction

This article will guide you through creating a simplified serverless e-commerce store. We'll use React for the user interface and Stripe Functions (using a serverless environment like Netlify Functions or AWS Lambda) for secure payment processing.

Setting up the React Frontend

First, create a new React application using Create React App:

npx create-react-app my-ecommerce-store
cd my-ecommerce-store

Create a simple product component (e.g., Product.js):

// Product.js
import React from 'react';

function Product({ name, price, onAddToCart }) {
  return (
    <div>
      <h3>{name}</h3>
      <p>${price}</p>
      <button onClick={onAddToCart}>Add to Cart</button>
    </div>
  );
}

export default Product;

Implement a basic shopping cart functionality in your App.js:

// App.js
import React, { useState } from 'react';
import Product from './Product';

function App() {
  const [cart, setCart] = useState([]);

  const products = [
    { id: 1, name: 'Awesome T-Shirt', price: 25 },
    { id: 2, name: 'Cool Mug', price: 15 },
  ];

  const handleAddToCart = (product) => {
    setCart([...cart, product]);
  };

  return (
    <div>
      <h1>My E-commerce Store</h1>
      {products.map((product) => (
        <Product key={product.id} name={product.name} price={product.price} onAddToCart={() => handleAddToCart(product)} />
      ))}
      <h2>Cart</h2>
      {cart.length === 0 ? <p>Your cart is empty.</p> : (
        <ul>
          {cart.map((item, index) => (
            <li key={index}>{item.name} - ${item.price}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;

Creating the Stripe Function (Backend)

This part assumes you have a Stripe account and have obtained your secret key. Create a serverless function (e.g., using Netlify Functions or AWS Lambda). For Netlify, you'd place this code in netlify/functions/create-payment-intent.js:

// netlify/functions/create-payment-intent.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

exports.handler = async (event) => {
  try {
    const { amount } = JSON.parse(event.body);

    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount,
      currency: 'usd',
      automatic_payment_methods: {
        enabled: true,
      },
    });

    return {
      statusCode: 200,
      body: JSON.stringify({ clientSecret: paymentIntent.client_secret }),
    };
  } catch (error) {
    console.log({ error });

    return {
      statusCode: 400,
      body: JSON.stringify({ error: error.message }),
    };
  }
};

Important: Set the STRIPE_SECRET_KEY environment variable in your hosting provider (Netlify, AWS, etc.).

Integrating with the Frontend

Now, call this function from your React frontend to create a Payment Intent:

// In App.js (modified)

// ... previous code ...

  const handleCheckout = async () => {
    const totalPrice = cart.reduce((sum, item) => sum + item.price, 0);

    const response = await fetch('/.netlify/functions/create-payment-intent', { // Adjust if not using Netlify
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount: totalPrice * 100 }), // Amount in cents
    });

    const { clientSecret } = await response.json();

    // Redirect to Stripe Checkout or use Stripe Elements to complete the payment
    // (This part requires integrating the Stripe.js library – refer to Stripe documentation)
    console.log("Client Secret:", clientSecret); // Placeholder - Implement Stripe Checkout flow here
  };

  return (
    <div>
      {/* ... previous code ... */}
      <button onClick={handleCheckout}>Checkout</button>
    </div>
  );

Note: This is a highly simplified example. You will need to implement the full Stripe Checkout or Stripe Elements flow using the clientSecret returned from the serverless function. See Stripe's documentation for details.

Conclusion

This provides a basic structure for a serverless e-commerce store. Remember to implement proper error handling, security measures, and a complete Stripe integration for a production-ready application.