Skip to content
Β 
Β 

Latest commit

Β 

History

103 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

License: CC BY-NC 4.0 Next.js React Sanity Clerk pesapal AI

πŸ›‹οΈ AI-Powered E-commerce Platform with Real-time Content

Build a modern Afrigoals e-commerce store with an AI shopping assistant, real-time inventory updates, and a powerful admin dashboard β€” all powered by cutting-edge technologies.

πŸ‘₯ Who It's For ⚑ Key Differentiators πŸ”§ Technical Highlights
Developers learning modern full-stack patterns with AI integration Sanity App SDK for real-time data & Clerk AgentKit for authenticated AI tools Claude AI shopping assistant, live inventory updates, pesapal checkout

πŸ‘‡πŸΌ DO THIS Before You Get Started

Use THESE links to set up your accounts (It's a special affiliate link which lets us continue to do builds like this FREE for you!):

Service Description ‼️ LINK TO USE ‼️
🧑 Sanity Headless CMS with real-time capabilities & App SDK Get Started with Sanity β†’
πŸ’œ Clerk Authentication with AgentKit for AI context Get Started with Clerk β†’

πŸ€” What Is This App?

Think of it as a sports merchandise store with a brain.

This is a full-featured e-commerce platform where customers can:

  • πŸ›’ Browse & Buy β€” Shop premium sports merchandise with real-time stock updates
  • πŸ€– Chat with AI β€” Ask the AI assistant to find products, check prices, or track orders
  • πŸ“¦ Track Orders β€” View order history and delivery status (when signed in)

And store owners get:

  • πŸ“Š AI-Powered Insights β€” Dashboard with sales trends, inventory alerts, and action items
  • ✏️ Real-time Editing β€” Manage products and orders with instant updates via Sanity App SDK
  • πŸ”” Smart Alerts β€” Low stock warnings and unfulfilled order notifications

Key Concepts Explained

Term What It Means
CMS (Content Management System) Where all your products, orders, and content live β€” in this case, Sanity
Real-time Content When you update a product in Sanity, it instantly appears on the website
AI Shopping Assistant A chatbot powered by Claude AI that can search products and check your orders
App SDK Sanity's toolkit for building custom applications with direct database access

🎯 What You'll Learn

βœ… Next.js 16 with App Router & Server/Client Components + Server Actions!

βœ… Clerk authentication with AgentKit for AI-aware user context!

βœ… Sanity CMS with App SDK for real-time data mutations & live content updates!

βœ… Vercel AI SDK with AI Gateway for multi-provider LLM support (Claude, GPT, Cohere)!

βœ… pesapal payments with webhooks for secure checkout & order processing!

βœ… shadcn/ui + Tailwind CSS v4 for beautiful, accessible UI components!

βœ… Zustand state management with localStorage persistence for cart!

βœ… Mobile-responsive design with modern layouts & dark mode!

βœ… AI Shopping Assistant with custom tools for product search & order tracking!

βœ… AI Admin Dashboard with Claude-powered insights, sales trends & recommendations!

βœ… GROQ queries with TypeGen for type-safe Sanity data fetching!

βœ… Real-time UI updates via Sanity Live β€” no polling required!

βœ… Custom AI tools scoped to authenticated users (orders only visible when signed in)!

βœ… Webhook-driven order creation with automatic stock management!

βœ… Embedded Sanity Studio for content management at /studio! + SO MUCH MORE!


πŸš€ Before We Dive In - Join the PAPAFAM!

Want to build apps like this from scratch?

Join thousands of developers learning to build production-ready applications with the latest technologies.

PAPAFAM Community Benefits

  • πŸŽ“ Step-by-step video tutorials
  • πŸ’¬ Private Discord community
  • πŸ”₯ Weekly coding challenges
  • πŸ“ Access to all project source code
  • πŸ† Certificate of completion

Real Results

"I landed my first developer job after completing the PAPAFAM course!" β€” Community Member


✨ Features

For Shoppers

Feature Description
πŸ€– AI Shopping Assistant Natural language product search, filter by material/color/price, get recommendations
πŸ“¦ Order Tracking View your order history and status (requires sign-in)
πŸ›’ Smart Cart Persistent cart with real-time stock validation
πŸ’³ Secure Checkout pesapal-powered payments with address collection
πŸ”„ Real-time Stock See live inventory levels β€” no surprises at checkout

For Admins

Feature Description
🧠 AI Dashboard Insights Sales trends, inventory alerts, and actionable recommendations powered by Claude
πŸ“ Product Management Create, edit, and publish products directly via Sanity App SDK
πŸ“‹ Order Management Update order status (paid β†’ shipped β†’ delivered)
⚠️ Low Stock Alerts Automatic warnings when inventory runs low
πŸ“Š Analytics Revenue tracking, order counts, and performance metrics

Technical Features (The Smart Stuff)

Feature Technology Why It Matters
⚑ Real-time Updates Sanity Live + App SDK Content changes appear instantly without refresh
πŸ” Authenticated AI Clerk AgentKit AI assistant knows who you are and can access YOUR orders
🧠 AI Gateway Vercel AI Gateway Use Claude, GPT, or other models β€” easily swappable
πŸ›’ Persisted Cart Zustand + localStorage Cart survives page refreshes and browser restarts
πŸ“± Responsive Design Tailwind CSS + Shadcn/UI Beautiful UI on any device
βš™οΈ Type Safety TypeScript + Sanity TypeGen Auto-generated types from your CMS schema

πŸ”„ How It Works

User Shopping Flow

flowchart LR
    A[Browse Products] --> B[Add to Cart]
    B --> C[Checkout]
    C --> D[pesapal Payment]
    D --> E[Webhook]
    E --> F[Order Created in Sanity]
    F --> G[Stock Updated]

    A --> H[Chat with AI]
    H --> I[Search Products]
    H --> J[Check Orders]
Loading

AI Assistant Architecture

flowchart TD
    A[User Message] --> B{Clerk Auth Check}
    B --> C[AI Agent - Claude Sonnet]
    C --> D{Tool Selection}

    D --> E[searchProducts]
    D --> F[getMyOrders]

    E --> G[GROQ Query to Sanity]
    G --> H[Product Results]

    F --> I{User Authenticated?}
    I -->|Yes| J[Fetch User Orders]
    I -->|No| K[Prompt to Sign In]

    H --> L[AI Response with Product Cards]
    J --> L
Loading

Real-time Data Flow

flowchart LR
    subgraph Sanity Cloud
        A[Sanity CMS]
    end

    subgraph Next.js App
        B[SanityLive Provider]
        C[Server Components]
        D[Sanity App SDK]
        E[Admin Dashboard]
    end

    A -->|Real-time sync| B
    B --> C
    C -->|Live UI updates| F[Customer View]

    D -->|Direct mutations| A
    E --> D
Loading

πŸš€ Getting Started

Prerequisites

Before you begin, ensure you have:

Step-by-Step Setup

1. Clone the Repository

git clone https://github.com/sonnysangha/ai-ecommerce-sanity-clerk.git
cd ai-ecommerce-sanity-clerk

2. Install Dependencies

pnpm install

3. Set Up Environment Variables

cp .env.example .env.local

Then fill in your values:

# Sanity
NEXT_PUBLIC_SANITY_PROJECT_ID=Your_value_goes_here
NEXT_PUBLIC_SANITY_DATASET=Your_value_goes_here
NEXT_PUBLIC_SANITY_ORG_ID=Your_value_goes_here
SANITY_API_WRITE_TOKEN=Your_value_goes_here

# Clerk
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=Your_value_goes_here
CLERK_SECRET_KEY=Your_value_goes_here

# pesapal
pesapal_SECRET_KEY=Your_value_goes_here
# pesapal listen --forward-to localhost:3000/api/webhooks/pesapal
pesapal_WEBHOOK_SECRET=Your_value_goes_here

# Vercel
AI_GATEWAY_API_KEY=Your_value_goes_here

⚠️ Security Note: Never commit .env.local to git. The .gitignore already excludes it.

πŸ’‘ Tip: Variables starting with NEXT_PUBLIC_ are exposed to the browser. Keep sensitive keys (like CLERK_SECRET_KEY) without this prefix.

4. Configure Sanity

  1. Go to sanity.io/manage
  2. Create a new project or select existing
  3. Copy your Project ID and Dataset name
  4. Create an API token with Editor permissions for SANITY_API_WRITE_TOKEN

5. Configure Clerk

  1. Go to dashboard.clerk.com
  2. Create a new application
  3. Copy your Publishable Key and Secret Key

6. Configure pesapal

  1. Go to dashboard.pesapal.com/apikeys
  2. Copy your Secret Key (starts with sk_test_ for development)
  3. For webhooks, run the pesapal CLI:
pesapal listen --forward-to localhost:3000/api/webhooks/pesapal
  1. Copy the webhook signing secret it provides

7. Configure AI Gateway

  1. Go to vercel.com and navigate to AI Gateway
  2. Create an API key
  3. The app uses Claude Sonnet 4/4.5 by default, but you can swap to other providers

πŸ’‘ Swappable Models: The AI Gateway supports OpenAI, Anthropic, Cohere, and more. Check lib/ai/shopping-agent.ts to change models.

8. Generate Types & Import Data

# Generate TypeScript types from Sanity schema
pnpm typegen

# Import sample sports merchandisedata
npx sanity dataset import sample-data.ndjson

9. Start Development Server

pnpm dev

Open http://localhost:3000 β€” you're ready to go! πŸŽ‰

First Time Setup Checklist

  • All environment variables filled in .env.local
  • Sanity project created with dataset
  • Clerk application created
  • pesapal CLI running for local webhooks
  • Sample data imported
  • Types generated with pnpm typegen

πŸ“Š Database Schema Overview

This app uses Sanity as its headless CMS with the following document types:

Product

Field Type Description
name string Product name
slug slug URL-friendly identifier
description text Product description
price number Price in GBP
category reference Link to category
material string wood, metal, fabric, leather, glass
color string black, white, oak, walnut, grey, natural
dimensions string e.g., "120cm x 80cm x 75cm"
stock number Current inventory count
images array Product images with hotspot
featured boolean Show in featured carousel

Category

Field Type Description
title string Category name
slug slug URL-friendly identifier
description text Category description
image image Category thumbnail

Order

Field Type Description
orderNumber string Unique order ID (e.g., ORD-ABC123)
items array Products with quantity and price at purchase
total number Order total in GBP
status string pending, paid, shipped, delivered, cancelled
customer reference Link to customer record
clerkUserId string Clerk user identifier
email string Customer email
address object Shipping address
pesapalPaymentId string pesapal payment intent ID

Customer

Field Type Description
name string Customer name
email string Customer email
clerkUserId string Clerk user identifier
pesapalCustomerId string pesapal customer ID

πŸ”§ Key Technical Patterns

Sanity App SDK Patterns

The admin dashboard uses Sanity App SDK for direct document operations:

// app/(admin)/admin/page.tsx
import {
  useApplyDocumentActions,
  createDocumentHandle,
  createDocument,
} from "@sanity/sdk-react";

// Create a new product
const apply = useApplyDocumentActions();

const handleCreateProduct = async () => {
  const newDocHandle = createDocumentHandle({
    documentId: crypto.randomUUID(),
    documentType: "product",
  });
  await apply(createDocument(newDocHandle));
  router.push(`/admin/inventory/${newDocHandle.documentId}`);
};

Key hooks used:

  • useDocuments() β€” Reactive document queries
  • useApplyDocumentActions() β€” Perform mutations (create, update, delete)
  • createDocumentHandle() β€” Create handles for new documents

Clerk AgentKit Pattern

The AI assistant uses Clerk to provide user context:

// lib/ai/shopping-agent.ts
export function createShoppingAgent({ userId }: { userId: string | null }) {
  const isAuthenticated = !!userId;

  // Tools vary based on authentication
  const tools: Record<string, Tool> = {
    searchProducts: searchProductsTool, // Always available
  };

  // Only add orders tool if user is signed in
  if (isAuthenticated) {
    tools.getMyOrders = createGetMyOrdersTool(userId);
  }

  return new ToolLoopAgent({
    model: gateway("anthropic/claude-sonnet-4.5"),
    instructions: isAuthenticated ? fullInstructions : guestInstructions,
    tools,
  });
}

How it works:

  1. Clerk provides userId from the session
  2. Agent is created with user-specific tools
  3. getMyOrders tool is scoped to that user's data

Custom AI Tools

searchProducts Tool

// lib/ai/tools/search-products.ts
export const searchProductsTool = tool({
  description: "Search for products in the sports merchandise store",
  inputSchema: z.object({
    query: z.string().optional(),
    category: z.string().optional(),
    material: z.enum(["", "wood", "metal", "fabric", "leather", "glass"]),
    color: z.enum(["", "black", "white", "oak", "walnut", "grey", "natural"]),
    minPrice: z.number().optional(),
    maxPrice: z.number().optional(),
  }),
  execute: async (params) => {
    // Executes GROQ query against Sanity
    const { data: products } = await sanityFetch({
      query: AI_SEARCH_PRODUCTS_QUERY,
      params,
    });
    return { products, found: products.length > 0 };
  },
});

getMyOrders Tool

// lib/ai/tools/get-my-orders.ts
export function createGetMyOrdersTool(userId: string | null) {
  if (!userId) return null; // Not available for guests

  return tool({
    description: "Get the current user's orders",
    inputSchema: z.object({
      status: z
        .enum(["", "pending", "paid", "shipped", "delivered"])
        .optional(),
    }),
    execute: async ({ status }) => {
      const { data: orders } = await sanityFetch({
        query: ORDERS_BY_USER_QUERY,
        params: { clerkUserId: userId },
      });
      return { orders, found: orders.length > 0 };
    },
  });
}

🚒 Deployment

Deploy to Vercel

Option 1: Vercel CLI

# Install Vercel CLI
pnpm install -g vercel

# Deploy
vercel

Option 2: GitHub Integration

  1. Push your code to GitHub
  2. Go to vercel.com/new
  3. Import your repository
  4. Add environment variables
  5. Deploy!

Post-Deployment Checklist

  • All environment variables set in Vercel dashboard
  • Update pesapal webhook URL to production: https://yourdomain.com/api/webhooks/pesapal
  • Add production domain to Clerk allowed origins
  • Add production domain to Sanity CORS origins
  • Test a complete purchase flow

Monitoring

  • Vercel Analytics β€” Performance and usage metrics
  • Sanity Studio β€” Content management at /studio
  • pesapal Dashboard β€” Payment monitoring
  • Clerk Dashboard β€” User analytics

πŸ› Common Issues & Solutions

Sanity Issues

Problem Solution
"Missing write token" error Ensure SANITY_API_WRITE_TOKEN is set with Editor permissions
CORS errors Add your domain to Sanity project CORS origins
Types out of sync Run pnpm typegen after schema changes

Clerk Issues

Problem Solution
Middleware not working Check middleware.ts matches Clerk docs
User not found in session Ensure ClerkProvider wraps your app
AgentKit not getting userId Verify auth() is called server-side

pesapal Issues

Problem Solution
Webhook signature failed Ensure pesapal_WEBHOOK_SECRET matches CLI output
Payment succeeded but no order Check webhook endpoint and Sanity write permissions
"API key invalid" Use test keys (sk_test_) for development

AI Issues

Problem Solution
"Gateway error" Verify AI_GATEWAY_API_KEY is valid
Rate limiting Implement request throttling or upgrade plan
Wrong model response Check model name in shopping-agent.ts

πŸ† Take It Further - Challenge Time!

Ready to level up? Try adding these features:

Beginner Challenges

  • Add product reviews with star ratings
  • Implement a wishlist/favorites feature
  • Add social sharing buttons

Intermediate Challenges

  • Email notifications via Resend
  • Product comparison feature
  • Advanced filtering (multiple selections)

Advanced Challenges

  • AI-powered product recommendations ("You might also like...")
  • Sentiment analysis for reviews
  • Multi-currency support with automatic conversion
  • Inventory forecasting with AI

Infrastructure Challenges

  • Add Redis caching for frequently accessed products
  • Implement image optimization with Cloudinary
  • Add full-text search with Algolia

πŸ“„ License

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0).

βœ… You CAN

  • Use this code for personal learning
  • Modify and adapt the code
  • Share with attribution
  • Use in portfolio projects

❌ You CANNOT

  • Use for commercial purposes without permission
  • Sell this code or derivatives
  • Remove attribution

πŸ’Ό Commercial Licensing

Want to use this for a commercial project? Contact us:

πŸ“§ contact@papareact.com

See LICENSE.md for full details.


πŸ“š Quick Reference

Useful Commands

Command Description
pnpm dev Start development server
pnpm build Build for production
pnpm start Start production server
pnpm typegen Generate TypeScript types from Sanity schema
pnpm lint Run Biome linter
pnpm format Format code with Biome
pnpm typecheck Run TypeScript type checking

Key Files & Folders

β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ (app)/              # Customer-facing routes
β”‚   β”œβ”€β”€ (admin)/admin/      # Admin dashboard
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ chat/           # AI chat endpoint
β”‚   β”‚   └── webhooks/pesapal # pesapal webhook handler
β”‚   └── studio/             # Embedded Sanity Studio
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ app/                # Customer UI components
β”‚   β”œβ”€β”€ admin/              # Admin UI components
β”‚   └── ui/                 # Shadcn/UI components
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ ai/                 # AI agent & tools
β”‚   β”œβ”€β”€ sanity/queries/     # GROQ queries
β”‚   └── store/              # Zustand stores
β”œβ”€β”€ sanity/
β”‚   β”œβ”€β”€ schemaTypes/        # Sanity document schemas
β”‚   └── lib/                # Sanity client & utilities
└── .env.example            # Environment template

Important Concepts

Concept File(s) What It Does
Shopping Agent lib/ai/shopping-agent.ts Configures AI with tools and instructions
Search Tool lib/ai/tools/search-products.ts AI tool for product search
Orders Tool lib/ai/tools/get-my-orders.ts AI tool for user's order history
Real-time Data sanity/lib/live.ts Sanity Live configuration
Cart Store lib/store/cart-store.ts Zustand cart with persistence
Admin Actions app/(admin)/admin/page.tsx Sanity App SDK document operations

Built with ❀️ by Sonny Sangha & the PAPAFAM Community

YouTube Β· Twitter Β· Course

Releases

Packages

Contributors

Languages