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

# NextAPI + Bun Setup

> This configuration combines Next.js API routes with Bun's fast runtime. It provides the best of both worlds: Next.js's familiar API structure with Bun's performance benefits.

<Warning>
  **Important:** For NextAPI configurations, you need to copy all variables from
  `server/.env` to `web/.env` because the API routes run within the Next.js
  application.
</Warning>

### What You'll Get

* **Backend:** Next.js API routes
* **Runtime:** Bun (fast JavaScript runtime)
* **Bundler:** Bun's built-in bundler
* **Performance:** Excellent startup time
* **Structure:** API routes within Next.js app

***

## Prerequisites

Before starting, ensure you have:

* [Bun](https://bun.sh) v1.0+ installed
* [Git](https://git-scm.com/) for version control
* Access to your Builder Box dashboard

***

## Step 1: Project Setup

### 1.1 Access Your Dashboard

1. **Visit the Dashboard**

   * Go to: [https://www.builderbox.ai/bought/main](https://www.builderbox.ai/bought/main)
   * Log in with your account credentials

2. **Create Your Project**

   * Click **"Create Project"** on your dashboard
   * Select **"NextAPI + Bun"** as your backend configuration
   * Fill out the project configuration form
   * Click **"Create Project"** to generate your boilerplate

3. **Install Your Project**
   * Run the provided installation command:
     ```bash theme={null}
     npm install -g @humanoidz/builderbox && builderbox YOUR_PROJECT_ID
     ```

***

## Step 2: Environment Configuration

### 2.1 Web Environment Variables (Combined)

Create `apps/web/.env` with **ALL** environment variables:

```env theme={null}
# Database
DATABASE_URL=your_supabase_transaction_pooler_url
DIRECT_URL=your_supabase_session_pooler_url

# Authentication
BETTER_AUTH_SECRET=your_generated_secret
BETTER_AUTH_URL=http://localhost:3001
CORS_ORIGIN=http://localhost:3001

# Google OAuth
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret

# Email
RESEND_API_KEY=re_your_api_key

# Payments
STRIPE_SECRET_KEY=sk_test_your_secret_key
STRIPE_TEST_PRODUCT=price_your_price_id
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# AI
OPENROUTER_API_KEY=your_openrouter_api_key

# Frontend Configuration
NEXT_PUBLIC_SERVER_URL=http://localhost:3001
NEXT_PUBLIC_APP_URL=http://localhost:3001
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3003
```

<Info>
  **Key Difference:** Unlike Hono configurations, all environment variables are
  in `apps/web/.env` because the API routes run within the Next.js application.
</Info>

### 2.2 CMS Environment Variables

Create `apps/cms/.env`:

```env theme={null}
DATABASE_URI=your_cms_supabase_url
PAYLOAD_SECRET=your_generated_cms_secret
```

***

## Step 3: Database Setup

### 3.1 Run Database Commands

```bash theme={null}
# Navigate to the project root
cd your-project-name

# Generate Prisma client
bun run db:generate

# Create initial migration
bun run db:migrate

# Push schema changes
bun run db:push
```

***

## Step 4: Start Development

### 4.1 Start All Services

```bash theme={null}
# From the root directory
bun dev
```

This will start:

* **Frontend App (Next.js + API routes)** on port 3001
* **CMS** on port 3003

### 4.2 Individual Services (Optional)

If you prefer to run services separately:

**Terminal 1 - Frontend + API:**

```bash theme={null}
cd apps/web
bun dev
```

**Terminal 2 - CMS:**

```bash theme={null}
cd apps/cms
bun dev
```

***

## Step 5: Verify Setup

### 5.1 Check Services

* **Frontend + API:** [http://localhost:3001](http://localhost:3001)
* **CMS:** [http://localhost:3003](http://localhost:3003)

### 5.2 Test API Endpoints

```bash theme={null}
# Health check
curl http://localhost:3001/api/trpc/healthCheck

# Should return: {"message":"OK"}
```

***

## Project Structure

```
your-project/
├── apps/
│   ├── web/             # Next.js frontend + API routes
│   │   ├── src/
│   │   │   ├── app/     # Next.js app router
│   │   │   │   └── api/ # API routes
│   │   │   └── lib/     # Utilities
│   │   └── package.json
│   └── cms/             # Payload CMS
│       ├── src/
│       └── package.json
├── packages/            # Shared packages
└── package.json         # Root package.json
```

***

## Key Features

### Next.js API Routes Benefits

* **Unified Codebase:** Frontend and backend in one project
* **Type Safety:** Full TypeScript support
* **Middleware:** Next.js middleware support
* **Deployment:** Easy deployment to Vercel
* **Familiarity:** Standard Next.js patterns

### Bun Runtime Benefits

* **Speed:** Faster startup and execution
* **Memory:** Lower memory usage
* **Bundler:** Built-in bundler for production builds
* **Compatibility:** Full Node.js compatibility
* **Developer Experience:** Fast package installation

***

## Development Commands

| Command           | Description            |
| ----------------- | ---------------------- |
| `bun dev`         | Start all services     |
| `bun build`       | Build for production   |
| `bun dev:web`     | Frontend + API only    |
| `bun check-types` | TypeScript validation  |
| `bun db:push`     | Update database schema |
| `bun db:studio`   | Database management UI |

***

## Environment Variables Management

### Important Notes

1. **Single Environment File:** All variables are in `apps/web/.env`
2. **API Routes Access:** Environment variables are accessible in API routes
3. **Client Variables:** Use `NEXT_PUBLIC_` prefix for client-side variables
4. **Security:** Never expose sensitive variables to the client

### Variable Categories

```env theme={null}
# Server-side only (not exposed to client)
DATABASE_URL=...
BETTER_AUTH_SECRET=...
STRIPE_SECRET_KEY=...

# Client-side accessible
NEXT_PUBLIC_APP_URL=...
NEXT_PUBLIC_SERVER_URL=...
```

***

## Performance Benefits

### Bun vs Node.js for Next.js

| Aspect               | Bun   | Node.js |
| -------------------- | ----- | ------- |
| Startup Time         | ⭐⭐⭐⭐⭐ | ⭐⭐⭐     |
| Memory Usage         | ⭐⭐⭐⭐⭐ | ⭐⭐⭐     |
| Package Installation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐     |
| Hot Reload           | ⭐⭐⭐⭐⭐ | ⭐⭐⭐     |
| Build Speed          | ⭐⭐⭐⭐⭐ | ⭐⭐⭐     |

### Optimization Tips

1. **Use Bun's Built-in Bundler:**

   ```bash theme={null}
   # Faster builds with Bun
   bun run build
   ```

2. **Leverage Bun's Package Manager:**

   ```bash theme={null}
   # Faster package installation
   bun install
   ```

3. **Enable Bun's Optimizations:**
   ```typescript theme={null}
   // Use Bun's native APIs where possible
   const file = Bun.file("data.json");
   const data = await file.json();
   ```

***

## Troubleshooting

### Common Issues

**🔥 "Bun not found"**

```bash theme={null}
# Install Bun
curl -fsSL https://bun.sh/install | bash
```

**🔥 "Environment variables not found"**

* Ensure all variables are in `apps/web/.env`
* Check for typos in variable names
* Restart the development server

**🔥 "Port already in use"**

```bash theme={null}
# Kill existing processes
lsof -ti:3001 | xargs kill -9
```

**🔥 "Database connection failed"**

* Verify your Supabase connection strings
* Ensure your database is running
* Check environment variables in `apps/web/.env`

**🔥 "Authentication not working"**

* Verify Google OAuth configuration
* Check BETTER\_AUTH\_SECRET is set
* Ensure CORS\_ORIGIN is correct

**🔥 "Build errors with Bun"**

```bash theme={null}
# Clear cache and reinstall
rm -rf node_modules
bun install
```

***

## Migration from Node.js

If you're migrating from Node.js to Bun:

1. **Update Package Manager:**

   ```bash theme={null}
   # Replace npm commands with bun
   npm install → bun install
   npm run dev → bun dev
   ```

2. **Update Scripts:**

   ```json theme={null}
   {
     "scripts": {
       "dev": "bun --bun next dev",
       "build": "bun --bun next build",
       "start": "bun --bun next start"
     }
   }
   ```

3. **Install Bun:**
   ```bash theme={null}
   curl -fsSL https://bun.sh/install | bash
   ```

***

## Deployment Considerations

### Vercel Deployment

This configuration works excellently with Vercel:

1. **Connect to Vercel:**

   ```bash theme={null}
   npm install -g vercel
   vercel
   ```

2. **Environment Variables:**

   * Add all variables to Vercel dashboard
   * Use `NEXT_PUBLIC_` prefix for client variables

3. **Build Configuration:**
   ```json theme={null}
   {
     "buildCommand": "bun run build",
     "installCommand": "bun install"
   }
   ```

### Other Platforms

* **Railway:** Supports Bun runtime
* **DigitalOcean App Platform:** Supports Bun
* **Docker:** Use Bun base image

***

## Next Steps

🎉 **Congratulations!** Your NextAPI + Bun setup is complete. Here's what you can do next:

1. **Customize the frontend** - Edit components in `apps/web/src/components`
2. **Add API endpoints** - Create new routes in `apps/web/src/app/api`
3. **Configure CMS** - Add content types in `apps/cms/src/collections`
4. **Set up production** - Deploy to Vercel for optimal performance
5. **Add features** - Extend with additional integrations

**Happy building!** 🚀
