{"id":50849374,"url":"https://github.com/chatbotkit/template-nextjs-chat-auth-stripe-js","last_synced_at":"2026-06-14T12:30:55.221Z","repository":{"id":350003833,"uuid":"1161036830","full_name":"chatbotkit/template-nextjs-chat-auth-stripe-js","owner":"chatbotkit","description":"Chat + Auth + Stripe template built with Next.js and ChatBotKit SDK","archived":false,"fork":false,"pushed_at":"2026-04-08T12:40:03.000Z","size":136,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-08T14:32:01.171Z","etag":null,"topics":["ai","chatbot","chatbotkit","javascript","next-auth","nextjs","streaming","stripe","template"],"latest_commit_sha":null,"homepage":"https://chatbotkit.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chatbotkit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-18T16:58:05.000Z","updated_at":"2026-04-08T12:39:59.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/chatbotkit/template-nextjs-chat-auth-stripe-js","commit_stats":null,"previous_names":["chatbotkit/template-nextjs-chat-auth-stripe-js"],"tags_count":null,"template":true,"template_full_name":null,"purl":"pkg:github/chatbotkit/template-nextjs-chat-auth-stripe-js","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chatbotkit","download_url":"https://codeload.github.com/chatbotkit/template-nextjs-chat-auth-stripe-js/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34322072,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-14T02:00:07.365Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","chatbot","chatbotkit","javascript","next-auth","nextjs","streaming","stripe","template"],"created_at":"2026-06-14T12:30:54.527Z","updated_at":"2026-06-14T12:30:55.216Z","avatar_url":"https://github.com/chatbotkit.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Chat + Auth + Stripe Template for Next.js / ChatBotKit / JS\n\nA production-ready chat application template with authentication, conversation persistence, and full ChatBotKit platform integration - built with Next.js, ChatBotKit SDK, next-auth, and shadcn/ui.\n\n\u003cimg width=\"50%\" src=\"https://github.com/user-attachments/assets/689727d4-082f-4902-8d92-1c5aea35dad0\" /\u003e\n\n\u003e **Note:** This template is deliberately bare-bones. It provides the minimal structure and wiring needed to get a working app, intentionally leaving styling, layout, and architectural choices open so you can build on top without fighting existing opinions.\n\n## Why ChatBotKit?\n\nBuilding an AI chat product typically means sourcing models, a conversation layer, background processing, storage, a tested abilities catalogue, authentication, security, monitoring, and more from separate systems. The cost adds up fast - not just in money, but in engineering time.\n\nChatBotKit brings all of this into one platform. This template gets you started with a monetizable chat app where your agents, skills, datasets, third-party integrations, guardrails, and conversation history are all managed through a single API - no need to stitch together disparate services.\n\n## Features\n\n- **Authentication** - Google OAuth via next-auth with JWT sessions\n- **Protected Routes** - Middleware-based route protection for `/chat`\n- **Streaming Chat** - Real-time AI responses using ChatBotKit streaming with `onStart`/`onFinish` lifecycle hooks\n- **Platform Agents** - Select from your ChatBotKit bots via a dropdown (with optional filtering via `CHATBOTKIT_BOT_IDS`)\n- **Conversation Persistence** - Conversations are saved to the platform and associated with contacts, so users can resume past conversations\n- **Conversation History** - Slide-out sidebar showing previous conversations with auto-generated labels\n- **Contact Tracking** - Authenticated users are automatically mapped to ChatBotKit contacts by email\n- **Stripe Billing** - Subscription checkout, trials, billing portal, and access gating for SaaS-style plans\n- **Modern UI** - Built with shadcn/ui components and Tailwind CSS\n- **Server Actions** - Next.js server actions for secure API communication (API keys never reach the client)\n\n## Technology Stack\n\n- **Next.js 14** - App Router with server actions\n- **ChatBotKit SDK** - `@chatbotkit/react` for client-side streaming, `@chatbotkit/sdk` for server-side API\n- **next-auth** - Authentication with Google OAuth provider (extensible to GitHub, email, etc.)\n- **shadcn/ui** - Accessible UI components built on Radix primitives\n- **Tailwind CSS** - Utility-first styling with dark mode support\n\n## Setup\n\n### Prerequisites\n\n- Node.js 18+\n- A [ChatBotKit](https://chatbotkit.com) account with at least one bot configured\n- Google OAuth credentials (for authentication)\n\n### Automated Setup\n\n```bash\nnpx create-cbk-app\n```\n\nFollow the prompts and configure environment variables (see below).\n\n### Manual Setup\n\n```bash\n# Clone the repository\ngit clone \u003crepo-url\u003e\ncd template-nextjs-chat-auth-stripe-js\n\n# Install dependencies\nnpm install\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your values (see Environment Variables below)\n\n# Start the development server\nnpm run dev\n```\n\nOpen [http://localhost:3000](http://localhost:3000) to get started.\n\n## Environment Variables\n\n| Variable                | Required | Description                                                                       |\n| ----------------------- | -------- | --------------------------------------------------------------------------------- |\n| `CHATBOTKIT_API_SECRET` | Yes      | ChatBotKit API token from [chatbotkit.com/tokens](https://chatbotkit.com/tokens)  |\n| `CHATBOTKIT_BOT_IDS`    | No       | Comma-separated bot IDs to show (e.g., `bot_abc,bot_def`). Omit to show all bots. |\n| `NEXTAUTH_SECRET`       | Yes      | Random secret for JWT signing - generate with `openssl rand -base64 32`           |\n| `NEXTAUTH_URL`          | Yes      | Your app URL (e.g., `http://localhost:3000`)                                      |\n| `GOOGLE_CLIENT_ID`      | Yes      | Google OAuth client ID                                                            |\n| `GOOGLE_CLIENT_SECRET`  | Yes      | Google OAuth client secret                                                        |\n| `STRIPE_SECRET_KEY`     | Yes\\*    | Stripe secret API key                                                             |\n| `STRIPE_PRICE_MONTHLY`  | Yes\\*    | Stripe Price ID for your monthly subscription                                     |\n| `STRIPE_PRICE_YEARLY`   | No       | Stripe Price ID for your yearly subscription                                      |\n| `STRIPE_TRIAL_DAYS`     | No       | Trial length in days for new subscriptions (default: `14`)                        |\n| `STRIPE_WEBHOOK_SECRET` | No       | Stripe webhook signing secret for `/api/stripe/webhook`                           |\n\n\\* Required only when you want to enforce paid access.\n\n\u003e **Note:** The AI model, backstory, skills, datasets, and all other agent configuration is managed per-bot on the [ChatBotKit platform](https://chatbotkit.com). Your app simply references the bot by ID - all capabilities come from the platform.\n\n### Setting Up ChatBotKit\n\n1. Sign up or log in at [chatbotkit.com](https://chatbotkit.com)\n2. Go to [chatbotkit.com/tokens](https://chatbotkit.com/tokens) and create an API token\n3. Create at least one bot and configure it with:\n   - A **backstory** describing the agent's personality and purpose\n   - A **model** (e.g., GPT-5.4 Mini, Claude Sonnet 4.6)\n   - Optional: a **skillset** with abilities and **datasets** for RAG\n4. Copy the API token to `CHATBOTKIT_API_SECRET` in your `.env` file\n5. The bot will appear in the agent dropdown. Optionally set `CHATBOTKIT_BOT_IDS` to restrict which bots are shown.\n\n### Getting Google OAuth Credentials\n\n1. Go to [Google Cloud Console](https://console.cloud.google.com/apis/credentials)\n2. Create a new OAuth 2.0 Client ID\n3. Set authorized redirect URI to `http://localhost:3000/api/auth/callback/google`\n4. Copy the Client ID and Client Secret to your `.env` file\n\n## How It Works\n\n### Architecture\n\n```\nBrowser (React)          Server Actions           ChatBotKit Platform\n┌──────────────┐        ┌──────────────┐         ┌──────────────────┐\n│ ConversationManager │──→│ complete()   │──→│ streamComplete()   │\n│ (streaming client)  │←──│ onStart()    │   │ Bot config + skills│\n│                     │   │ onFinish()   │   │ Datasets + RAG     │\n│ Bot Selector        │──→│ listBots()   │──→│ Contacts           │\n│ Conversation Sidebar│──→│ listConvos() │──→│ Conversations      │\n└──────────────┘        └──────────────┘         └──────────────────┘\n```\n\n1. **Authentication** - User signs in via Google OAuth. The session is JWT-based (24h expiry).\n2. **Contact Resolution** - On first chat load, the user's email is used to ensure a contact exists on the ChatBotKit platform via `cbk.contact.ensure()`.\n3. **Bot Selection** - Available bots are fetched from the platform. The user selects one from the dropdown.\n4. **Streaming** - Messages are sent via server actions. The `streamComplete` function streams the response token-by-token back to the browser.\n5. **Persistence** - `onStart` creates a conversation on the platform; `onFinish` saves all messages and generates a label. The conversation is linked to the contact.\n6. **History** - The sidebar fetches past conversations for the current contact and allows resuming them.\n7. **Billing Gate** - Chat routes and server actions check Stripe subscription/trial status before allowing access.\n\n### Stripe SaaS Billing Flow\n\n1. Authenticated users who are not on an active/trialing plan are redirected from `/chat` to `/billing`.\n2. The billing page creates Stripe Checkout sessions in subscription mode.\n3. Returning subscribers can manage plans/cancellations through Stripe Billing Portal.\n4. Every chat server action re-checks Stripe status, so expired subscriptions cannot continue using chat.\n5. Optional webhook endpoint (`/api/stripe/webhook`) validates Stripe events and revalidates billing/chat routes.\n\n### Stripe Webhook (Optional but Recommended)\n\n1. In Stripe Dashboard, add an endpoint: `https://your-domain.com/api/stripe/webhook`\n2. Subscribe to these events:\n   - `customer.subscription.created`\n   - `customer.subscription.updated`\n   - `customer.subscription.deleted`\n   - `invoice.paid`\n   - `invoice.payment_failed`\n   - `checkout.session.completed`\n3. Copy the webhook signing secret to `STRIPE_WEBHOOK_SECRET`\n\n### Stateless Streaming with Server-Side Persistence\n\nThe chat uses a **stateless streaming** pattern - the full message history is sent with every request (no server-side session). Persistence is handled via lifecycle callbacks:\n\n- **`onStart`** - Creates a new conversation on the platform (or reuses an existing one) and links it to the contact and bot.\n- **`onFinish`** - Saves all messages to the conversation and generates a human-readable label from the first exchange.\n\nThis gives you the simplicity of stateless streaming with the durability of platform-managed conversations.\n\n## Project Structure\n\n```\n├── actions/\n│   ├── billing.js           # Server actions for checkout + portal redirects\n│   └── conversation.jsx      # Server actions: complete, listBots, listConversations, etc.\n├── app/\n│   ├── layout.jsx            # Root layout with providers\n│   ├── page.jsx              # Landing page (redirects to /chat or /auth)\n│   ├── auth/signin/page.jsx  # Custom sign-in page\n│   ├── billing/page.jsx      # Billing and subscription management page\n│   ├── chat/\n│   │   ├── page.jsx          # Chat page (server component, session gate)\n│   │   └── chat-page.jsx     # Chat page (client component, all state)\n│   └── api/auth/[...nextauth]/\n│       └── route.ts          # NextAuth API route\n│   └── api/stripe/webhook/\n│       └── route.js          # Stripe webhook validation endpoint\n├── components/\n│   ├── providers.jsx         # Session provider wrapper\n│   ├── chat/\n│   │   ├── bot-selector.jsx          # Agent/bot dropdown selector\n│   │   ├── chat-area.jsx             # Chat container with ConversationManager\n│   │   ├── chat-header.jsx           # Header with sidebar toggle and user menu\n│   │   ├── chat-input.jsx            # Auto-resizing textarea with Enter-to-send\n│   │   ├── chat-messages.jsx         # Message bubbles with copy-to-clipboard\n│   │   └── conversation-sidebar.jsx  # Slide-out conversation history panel\n│   └── ui/                   # shadcn/ui primitives (avatar, button, card, etc.)\n├── hooks/\n│   └── useAutoRevert.js      # Auto-reverting state hook\n├── lib/\n│   ├── auth-options.js       # NextAuth configuration\n│   ├── billing.js            # Stripe billing status and plan helpers\n│   ├── stripe.js             # Stripe SDK singleton\n│   └── utils.js              # cn() utility for Tailwind class merging\n└── middleware.ts              # JWT-based route protection\n```\n\n## Customization\n\n### Platform Agents\n\nThe template fetches your bots directly from the ChatBotKit platform. To configure agents:\n\n1. Go to [chatbotkit.com](https://chatbotkit.com) and create bots\n2. Configure each bot's backstory, model, skills, datasets, and integrations\n3. The bots will automatically appear in the agent dropdown\n4. Optionally set `CHATBOTKIT_BOT_IDS` in `.env` to restrict which bots are shown\n\nWhen a bot is selected, its **full platform configuration** is used - including all skills, datasets, connected services, and guardrails. You can update any of these on the platform and the changes take effect immediately, without redeploying your app.\n\n### Filter Available Bots\n\nTo only show specific bots in the dropdown, set `CHATBOTKIT_BOT_IDS`:\n\n```env\nCHATBOTKIT_BOT_IDS=bot_abc123,bot_def456\n```\n\n### Add AI Functions (Client-Side)\n\nYou can also add client-side functions to the `functions` array in `actions/conversation.jsx`. These run alongside the platform-configured skills:\n\n```javascript\n{\n  name: 'lookupOrder',\n  description: 'Look up an order by ID',\n  parameters: {\n    type: 'object',\n    properties: {\n      orderId: { type: 'string', description: 'The order ID' },\n    },\n    required: ['orderId'],\n  },\n  handler: async ({ orderId }) =\u003e {\n    const order = await fetchOrder(orderId)\n    return { result: order }\n  },\n},\n```\n\n\u003e **Tip:** For most use cases, prefer adding skills on the ChatBotKit platform instead of hardcoding functions. Platform skills can be added, removed, and reconfigured without code changes.\n\n### Add More Auth Providers\n\nEdit `lib/auth-options.js` to add GitHub, email, or other providers:\n\n```javascript\nimport GitHubProvider from 'next-auth/providers/github'\n\nproviders: [\n  GoogleProvider({ ... }),\n  GitHubProvider({\n    clientId: process.env.GITHUB_CLIENT_ID,\n    clientSecret: process.env.GITHUB_CLIENT_SECRET,\n  }),\n],\n```\n\n## Learn More\n\n- [ChatBotKit Documentation](https://chatbotkit.com/docs)\n- [ChatBotKit SDK Reference](https://chatbotkit.com/docs/node-sdk)\n- [Next.js Documentation](https://nextjs.org/docs)\n- [next-auth Documentation](https://next-auth.js.org)\n- [shadcn/ui Documentation](https://ui.shadcn.com)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchatbotkit%2Ftemplate-nextjs-chat-auth-stripe-js/lists"}