> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rocket.new/llms.txt
> Use this file to discover all available pages before exploring further.

# Build an AI app

> Recipe for building an AI writing assistant in Rocket.new Build with chat UI, saved conversations, streaming responses, and Stripe subscription billing.

export const LlmsDirective = () => <blockquote className="llms-directive">
    For the complete documentation index, see <a href="/llms.txt">llms.txt</a>.
    For a lightweight markdown version of this page, append .md to the URL.
  </blockquote>;

<LlmsDirective />

<Info>
  An AI writing assistant where users chat with GPT to draft blog posts, edit copy, and brainstorm ideas. The app includes conversation history so users can pick up where they left off, user accounts with authentication, and a Pro subscription tier that unlocks unlimited messaging.

  By the end of this recipe you will have a production-ready AI app that you can customize, rebrand, and launch as your own product.
</Info>

## Tech stack

<Note>You do not need to understand these technologies. Rocket handles them automatically. This table is for reference.</Note>

| Integration              | What it does                                                  |
| ------------------------ | ------------------------------------------------------------- |
| **OpenAI**               | GPT models for chat completions and content generation        |
| **Supabase**             | User authentication, conversation storage, and usage tracking |
| **Stripe**               | Pro subscription billing (\$12/month)                         |
| **Resend**               | Welcome emails and daily usage alerts                         |
| **Netlify**              | One-click deployment to production                            |
| **Next.js + TypeScript** | App framework with server-side API routes                     |

## Architecture overview

Here is how data flows through the app:

1. **Sign in.** The user creates an account or logs in through Supabase Auth.
2. **Send a message.** The user types a prompt in the chat interface. The message is sent to an API route that calls the OpenAI Chat Completions endpoint.
3. **Stream the response.** GPT's response is streamed back to the browser in real time, token by token.
4. **Save the conversation.** Each message pair (user + assistant) is saved to a Supabase `messages` table, grouped by conversation.
5. **Track usage.** A counter in Supabase tracks how many messages the user has sent today.
6. **Enforce limits.** Free users are capped at 20 messages per day. When they hit the limit, the app shows an upgrade prompt.
7. **Upgrade.** Clicking "Upgrade to Pro" redirects to a Stripe Checkout session for the \$12/month plan.
8. **Send emails.** Resend delivers a welcome email on signup and a daily usage summary for Pro users.

## How long does it take?

| Phase          | What you are building         | Estimated time    |
| -------------- | ----------------------------- | ----------------- |
| Setup          | Project, Supabase, OpenAI     | 5-10 minutes      |
| Chat           | Interface, streaming, history | 10-15 minutes     |
| Business logic | Usage limits, Pro plan        | 5-10 minutes      |
| Communication  | Email notifications           | 5 minutes         |
| Launch         | Deploy, test, go live         | 5 minutes         |
| **Total**      | **Complete AI app**           | **30-45 minutes** |

## Step-by-step build

<Steps>
  <Step title="Start the project">
    Open [rocket.new](https://rocket.new) and describe the app you want to build. Be specific about the core features so Rocket generates a solid foundation.

    ```plaintext wrap theme={null}
    Build an AI writing assistant called "DraftAI". Users can sign in, start a new chat conversation with GPT, and get help drafting blog posts, editing copy, and brainstorming content ideas. The chat should feel fast and modern with a clean, minimal UI. Use Next.js with TypeScript and Tailwind CSS. Include a sidebar with a list of past conversations and a "New Chat" button.
    ```

    <Info>
      A detailed initial prompt saves you from reworking the layout later. Include the app name, core features, and UI preferences up front.
    </Info>
  </Step>

  <Step title="Connect Supabase for auth and data">
    Connect Supabase to handle user accounts and store all conversation data. Rocket will create the database tables and auth flow automatically.

    ```plaintext wrap theme={null}
    Connect Supabase. Set up email/password authentication with a sign-up page, login page, and protected routes. Create these database tables:
    - conversations: id, user_id, title, created_at, updated_at
    - messages: id, conversation_id, role (user or assistant), content, created_at
    - usage: id, user_id, date, message_count
    Add row-level security so users can only access their own data.
    ```
  </Step>

  <Step title="Connect OpenAI">
    Add your OpenAI API key so the app can send messages to GPT and receive completions.

    ```plaintext wrap theme={null}
    Connect OpenAI. Use the GPT-4o model for all chat completions. Add a system prompt that says: "You are DraftAI, a helpful writing assistant. You help users draft blog posts, edit copy, brainstorm ideas, and improve their writing. Be concise, clear, and encouraging. When asked to write content, match the tone the user requests."
    ```

    <Warning>
      Your OpenAI API key is billed separately by OpenAI based on token usage. Monitor your spending in the [OpenAI usage dashboard](https://platform.openai.com/usage).
    </Warning>
  </Step>

  <Step title="Build the chat interface with streaming">
    Make the chat feel responsive by streaming GPT's responses token by token instead of waiting for the full completion.

    ```plaintext wrap theme={null}
    Update the chat so that GPT responses stream in real time, word by word. Use the OpenAI streaming API. Show a typing indicator while the response is loading. Each message should display the sender (user or AI) with a subtle avatar. Add a text input at the bottom with a send button and support Enter to send. Auto-scroll to the latest message.
    ```

    <Info>
      Streaming makes the app feel much faster because users see the first words immediately instead of waiting several seconds for a complete response.
    </Info>
  </Step>

  <Step title="Add conversation history">
    Let users create multiple conversations, switch between them, and pick up past chats where they left off.

    ```plaintext wrap theme={null}
    Add conversation history. The sidebar should list all past conversations for the logged-in user, sorted by most recent. Clicking a conversation loads its full message history. Add a "New Chat" button at the top of the sidebar that creates a fresh conversation. Auto-generate a short title for each conversation based on the first user message. Add a delete button on each conversation with a confirmation dialog.
    ```
  </Step>

  <Step title="Implement usage limits for the free tier">
    Add a daily message cap for free users to control costs and incentivize upgrades.

    ```plaintext wrap theme={null}
    Add usage tracking. Free users can send up to 20 messages per day. Track the count in the usage table in Supabase, resetting at midnight UTC. Show a small counter in the chat header like "5 of 20 messages used today". When a free user hits 20 messages, disable the input and show a friendly banner that says "You've reached your daily limit. Upgrade to Pro for unlimited messages." with an upgrade button.
    ```

    <Info>
      Pick a daily limit that gives users enough value to see the product's potential while still creating a reason to upgrade. 20 messages is a good starting point.
    </Info>
  </Step>

  <Step title="Connect Stripe for the Pro plan">
    Add a paid tier that removes usage limits. Stripe handles the checkout, billing, and subscription management.

    ```plaintext wrap theme={null}
    Connect Stripe. Create a Pro plan at $12/month. Add a pricing section accessible from the sidebar and from the upgrade banner. The pricing page should show Free vs Pro with a feature comparison: Free: 20 messages/day, basic writing assistance, 5 saved conversations Pro: Unlimited messages, priority responses, unlimited saved conversations, export conversations as Markdown Use Stripe Checkout for payment. After successful payment, update the user's subscription status in Supabase and immediately unlock Pro features. Handle subscription cancellation and show billing status in account settings.
    ```

    <Warning>
      Start with Stripe Test mode keys during development. Use test card number `4242 4242 4242 4242` to simulate payments. Switch to Live keys only when you are ready to accept real payments.
    </Warning>
  </Step>

  <Step title="Add email notifications with Resend">
    Send a welcome email when users sign up and notify them about usage milestones.

    ```plaintext wrap theme={null}
    Connect Resend. Send these emails:
    1. Welcome email when a new user signs up, with a brief intro to DraftAI and tips for getting started.
    2. Upgrade confirmation email when a user subscribes to Pro, with a thank-you message and a summary of their new features.
    3. Usage alert email when a free user hits 15 of their 20 daily messages, nudging them toward the Pro plan.
    Use clean, minimal email templates that match the app's branding.
    ```
  </Step>

  <Step title="Deploy to Netlify and test end-to-end">
    Push the app to production and run through the full user journey.

    Use the **Launch** button in your Rocket project to deploy to the web. Rocket handles the Netlify build configuration automatically. Make sure all required environment variables are set in your project's integration settings before launching.

    **Test checklist:**

    * Sign up with a new email and verify the welcome email arrives
    * Start a conversation and confirm GPT responses stream correctly
    * Create multiple conversations and switch between them
    * Send 20 messages to trigger the usage limit banner
    * Complete a Stripe test checkout and verify Pro features unlock
    * Cancel the subscription and confirm the user reverts to the free tier
  </Step>

  <Step title="Go live">
    Once testing is complete, switch to production credentials and launch.

    * Switch Stripe to **live** mode keys in the project environment variables
    * Confirm Supabase row-level security is enabled on all tables
    * Verify the OpenAI system prompt does not leak sensitive information
    * Redeploy with the production environment variables
    * Connect a custom domain if you have one
  </Step>
</Steps>

## Customization ideas

<AccordionGroup>
  <Accordion title="Add multiple AI models" icon="brain">
    Let users choose between OpenAI GPT-4o, Anthropic Claude, and Google Gemini. Add a model selector dropdown in the chat header so users can switch models mid-conversation.

    ```plaintext wrap theme={null}
    Add a model selector dropdown in the chat header with three options: GPT-4o (OpenAI), Claude 3.5 Sonnet (Anthropic), and Gemini Pro (Google). Connect all three integrations. Default to GPT-4o. Show the active model name next to each AI response so users know which model generated it.
    ```
  </Accordion>

  <Accordion title="Add document upload and analysis" icon="file-arrow-up">
    Let users upload PDFs, text files, or Markdown documents and ask the AI to summarize, edit, or rewrite the content.

    ```plaintext wrap theme={null}
    Add a file upload button next to the chat input. Support PDF, TXT, and MD files up to 5MB. When a user uploads a file, extract the text content, include it in the conversation context, and show a preview card in the chat. The user can then ask questions about the document or request edits.
    ```
  </Accordion>

  <Accordion title="Add team workspaces" icon="users">
    Enable shared workspaces where team members can collaborate on conversations, share templates, and manage a shared Pro subscription.

    ```plaintext wrap theme={null}
    Add team workspaces. A user can create a team, invite members by email, and share conversations within the team. Add a workspace switcher in the sidebar for personal vs team spaces. Team conversations are visible to all members. The team admin manages the Stripe subscription for the whole team.
    ```
  </Accordion>

  <Accordion title="Add custom system prompts" icon="sliders">
    Let users create and save custom personas or writing styles that modify how the AI responds.

    ```plaintext wrap theme={null}
    Add a "Personas" section in settings where users can create custom system prompts. Each persona has a name and a system prompt, for example "Blog Editor" with the instruction "Edit the user's text for clarity, grammar, and flow. Return the edited version with tracked changes in Markdown." Let users select a persona before starting a new conversation.
    ```
  </Accordion>

  <Accordion title="Add voice input" icon="microphone">
    Let users speak their prompts instead of typing, using the browser's built-in speech recognition API.

    ```plaintext wrap theme={null}
    Add a microphone button next to the chat input that starts voice recording. Use the Web Speech API for speech-to-text. Show a pulsing animation while recording. When the user stops speaking, convert the audio to text and populate the chat input. The user can review and edit before sending.
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Responses appear all at once instead of streaming">
    If the full response loads after a long pause instead of appearing word by word, streaming may not be set up correctly. Ask Rocket to fix it:

    ```plaintext wrap theme={null}
    The chat responses are not streaming. Update the OpenAI API call to use streaming mode so the response appears word by word in real time instead of all at once after a delay.
    ```

    Also make sure your OpenAI integration is connected and your API key has sufficient credits.
  </Accordion>

  <Accordion title="Errors about message length or context limits">
    If you see errors when conversations get long, the chat history may be exceeding the model's limit. Ask Rocket to add a safeguard:

    ```plaintext wrap theme={null}
    I am getting context length errors on long conversations. Limit the chat history sent to OpenAI to the last 20 messages and add a summary of older messages so the AI still has background context.
    ```
  </Accordion>

  <Accordion title="'Too many requests' errors">
    If users see error messages when sending messages quickly, your OpenAI account may be hitting its rate limit. Ask Rocket to handle it gracefully:

    ```plaintext wrap theme={null}
    Users are seeing "too many requests" errors. Add rate limit handling that shows a friendly "Please try again in a few seconds" message and automatically retries the request after a short delay.
    ```

    If this happens frequently, you can request a higher rate limit from OpenAI in your [account settings](https://platform.openai.com/account/limits).
  </Accordion>

  <Accordion title="Conversations disappear on refresh">
    If messages vanish when you refresh the page or switch between conversations, they may not be saving to the database. Ask Rocket to debug:

    ```plaintext wrap theme={null}
    Messages are disappearing when I refresh or switch conversations. Make sure each message is being saved to the Supabase messages table after it is sent, and that the conversation loads all saved messages when I switch back to it. Add a notification if saving fails.
    ```
  </Accordion>
</AccordionGroup>
