← Discover MCPs and Agents
e
AgentAI & MLGitHub

ecommerce-ai-nextjs-16-sanity-clerk-agentkit-stripe-checkout-vercel-ai-agents

Links

README

From the repo.

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

🛋️ AI-Powered E-commerce Platform with Real-time Content

Build a modern furniture 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 ForKey Differentiators🔧 Technical Highlights
Developers learning modern full-stack patterns with AI integrationSanity App SDK for real-time data & Clerk AgentKit for authenticated AI toolsClaude AI shopping assistant, live inventory updates, Stripe 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!):

ServiceDescription‼️ LINK TO USE ‼️
🧡 SanityHeadless CMS with real-time capabilities & App SDKGet Started with Sanity →
💜 ClerkAuthentication with AgentKit for AI contextGet Started with Clerk →

🤔 What Is This App?

Think of it as a furniture store with a brain.

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

  • 🛒 Browse & Buy — Shop premium furniture 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

TermWhat It Means
CMS (Content Management System)Where all your products, orders, and content live — in this case, Sanity
Real-time ContentWhen you update a product in Sanity, it instantly appears on the website
AI Shopping AssistantA chatbot powered by Claude AI that can search products and check your orders
App SDKSanity'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)!

Stripe 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

FeatureDescription
🤖 AI Shopping AssistantNatural language product search, filter by material/color/price, get recommendations
📦 Order TrackingView your order history and status (requires sign-in)
🛒 Smart CartPersistent cart with real-time stock validation
💳 Secure CheckoutStripe-powered payments with address collection
🔄 Real-time StockSee live inventory levels — no surprises at checkout

For Admins

FeatureDescription
🧠 AI Dashboard InsightsSales trends, inventory alerts, and actionable recommendations powered by Claude
📝 Product ManagementCreate, edit, and publish products directly via Sanity App SDK
📋 Order ManagementUpdate order status (paid → shipped → delivered)
⚠️ Low Stock AlertsAutomatic warnings when inventory runs low
📊 AnalyticsRevenue tracking, order counts, and performance metrics

Technical Features (The Smart Stuff)

FeatureTechnologyWhy It Matters
Real-time UpdatesSanity Live + App SDKContent changes appear instantly without refresh
🔐 Authenticated AIClerk AgentKitAI assistant knows who you are and can access YOUR orders
🧠 AI GatewayVercel AI GatewayUse Claude, GPT, or other models — easily swappable
🛒 Persisted CartZustand + localStorageCart survives page refreshes and browser restarts
📱 Responsive DesignTailwind CSS + Shadcn/UIBeautiful UI on any device
⚙️ Type SafetyTypeScript + Sanity TypeGenAuto-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[Stripe 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]

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

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

🚀 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

# Stripe
STRIPE_SECRET_KEY=Your_value_goes_here
# stripe listen --forward-to localhost:3000/api/webhooks/stripe
STRIPE_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 Stripe

  1. Go to dashboard.stripe.com/apikeys
  2. Copy your Secret Key (starts with sk_test_ for development)
  3. For webhooks, run the Stripe CLI:
stripe listen --forward-to localhost:3000/api/webhooks/stripe
  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 furniture data
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
  • Stripe 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

FieldTypeDescription
namestringProduct name
slugslugURL-friendly identifier
descriptiontextProduct description
pricenumberPrice in GBP
categoryreferenceLink to category
materialstringwood, metal, fabric, leather, glass
colorstringblack, white, oak, walnut, grey, natural
dimensionsstringe.g., "120cm x 80cm x 75cm"
stocknumberCurrent inventory count
imagesarrayProduct images with hotspot
featuredbooleanShow in featured carousel

Category

FieldTypeDescription
titlestringCategory name
slugslugURL-friendly identifier
descriptiontextCategory description
imageimageCategory thumbnail

Order

FieldTypeDescription
orderNumberstringUnique order ID (e.g., ORD-ABC123)
itemsarrayProducts with quantity and price at purchase
totalnumberOrder total in GBP
statusstringpending, paid, shipped, delivered, cancelled
customerreferenceLink to customer record
clerkUserIdstringClerk user identifier
emailstringCustomer email
addressobjectShipping address
stripePaymentIdstringStripe payment intent ID

Customer

FieldTypeDescription
namestringCustomer name
emailstringCustomer email
clerkUserIdstringClerk user identifier
stripeCustomerIdstringStripe 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 furniture 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 Stripe webhook URL to production: https://yourdomain.com/api/webhooks/stripe
  • 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
  • Stripe Dashboard — Payment monitoring
  • Clerk Dashboard — User analytics

🐛 Common Issues & Solutions

Sanity Issues

ProblemSolution
"Missing write token" errorEnsure SANITY_API_WRITE_TOKEN is set with Editor permissions
CORS errorsAdd your domain to Sanity project CORS origins
Types out of syncRun pnpm typegen after schema changes

Clerk Issues

ProblemSolution
Middleware not workingCheck middleware.ts matches Clerk docs
User not found in sessionEnsure ClerkProvider wraps your app
AgentKit not getting userIdVerify auth() is called server-side

Stripe Issues

ProblemSolution
Webhook signature failedEnsure STRIPE_WEBHOOK_SECRET matches CLI output
Payment succeeded but no orderCheck webhook endpoint and Sanity write permissions
"API key invalid"Use test keys (sk_test_) for development

AI Issues

ProblemSolution
"Gateway error"Verify AI_GATEWAY_API_KEY is valid
Rate limitingImplement request throttling or upgrade plan
Wrong model responseCheck 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

CommandDescription
pnpm devStart development server
pnpm buildBuild for production
pnpm startStart production server
pnpm typegenGenerate TypeScript types from Sanity schema
pnpm lintRun Biome linter
pnpm formatFormat code with Biome
pnpm typecheckRun TypeScript type checking

Key Files & Folders

├── app/
│   ├── (app)/              # Customer-facing routes
│   ├── (admin)/admin/      # Admin dashboard
│   ├── api/
│   │   ├── chat/           # AI chat endpoint
│   │   └── webhooks/stripe # Stripe 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

ConceptFile(s)What It Does
Shopping Agentlib/ai/shopping-agent.tsConfigures AI with tools and instructions
Search Toollib/ai/tools/search-products.tsAI tool for product search
Orders Toollib/ai/tools/get-my-orders.tsAI tool for user's order history
Real-time Datasanity/lib/live.tsSanity Live configuration
Cart Storelib/store/cart-store.tsZustand cart with persistence
Admin Actionsapp/(admin)/admin/page.tsxSanity App SDK document operations

Built with ❤️ by Sonny Sangha & the PAPAFAM Community

YouTube · Twitter · Course

Collected info

  • 120 stars
  • 84 forks
  • Language: TypeScript
  • Source updated: 9/10/2026