# Build a Blog in 5 Minutes

This tutorial will take you from zero to a fully functional blog application with authentication, posts, comments, and a modern UI - all in about 5 minutes using Bangstack.

## What You'll Build

- **Frontend**: React with TypeScript, Tailwind CSS, and React Router
- **Backend**: Express API with TypeScript
- **Database**: PostgreSQL with Drizzle ORM
- **Features**: User authentication, blog posts, comments, and categories
- **Extras**: Docker support, tests, and CI/CD

## Prerequisites

- Node.js 18+ installed
- Docker Desktop (optional, for local database)
- 5 minutes of your time!

## Step 1: Install Bangstack (30 seconds)

```bash
npm install -g bangstack
```

Verify installation:
```bash
bang --version
```

## Step 2: Create Your Blog Workflow (2 minutes)

Let's use the interactive workflow creator to build our blog:

```bash
bang create
```

Answer the prompts as follows:

### Basic Information
```
? Workflow name: my-blog
? Description: A modern blog with posts, comments, and authentication
? What type of project are you building? full-stack
```

### Technology Stack
```
? Select frontend framework: React
? Include TypeScript for frontend? Yes
? Select CSS framework: Tailwind CSS
? Select backend framework: Express
? Include TypeScript for backend? Yes
? Select database: PostgreSQL
? Select ORM: Drizzle
? Do you want to add caching? No
```

### Features
```
? Add authentication system? Yes
? Generate tests? Yes
? Add Docker support? Yes
? Add CI/CD configuration? Yes
? Which CI/CD platform? GitHub Actions
```

### Data Models

Now let's define our blog data models. We'll create:
1. User (for authentication)
2. Post (blog posts)
3. Category (post categories)
4. Comment (post comments)

#### Model 1: User
```
? Do you want to define data models? Yes

? Model name (PascalCase): User
? Model description: Blog user with authentication

The following system fields will be added automatically:
- id (uuid, primary key)
- created_at (timestamp)
- updated_at (timestamp)

? Add a custom field? Yes
? Field name (snake_case): email
? Field type: string
? Field length/size: 255
? Required field? Yes
? Unique field? Yes

? Add a custom field? Yes
? Field name (snake_case): username
? Field type: string
? Field length/size: 100
? Required field? Yes
? Unique field? Yes

? Add a custom field? Yes
? Field name (snake_case): password_hash
? Field type: string
? Field length/size: 255
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): full_name
? Field type: string
? Field length/size: 200
? Required field? No
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): bio
? Field type: text
? Required field? No
? Unique field? No

? Add a custom field? No
```

#### Model 2: Post
```
? Add another model? Yes

? Model name (PascalCase): Post
? Model description: Blog post

? Add a custom field? Yes
? Field name (snake_case): title
? Field type: string
? Field length/size: 255
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): slug
? Field type: string
? Field length/size: 255
? Required field? Yes
? Unique field? Yes

? Add a custom field? Yes
? Field name (snake_case): content
? Field type: text
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): excerpt
? Field type: string
? Field length/size: 500
? Required field? No
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): status
? Field type: enum
? Enum values (comma-separated): draft,published,archived
? Required field? Yes
? Default value: draft

? Add a custom field? Yes
? Field name (snake_case): author_id
? Field type: uuid
? Is this a foreign key? Yes
? References which model? User
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): category_id
? Field type: uuid
? Is this a foreign key? Yes
? References which model? Category
? Required field? No
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): published_at
? Field type: timestamp
? Required field? No
? Unique field? No

? Add a custom field? No
```

#### Model 3: Category
```
? Add another model? Yes

? Model name (PascalCase): Category
? Model description: Post category

? Add a custom field? Yes
? Field name (snake_case): name
? Field type: string
? Field length/size: 100
? Required field? Yes
? Unique field? Yes

? Add a custom field? Yes
? Field name (snake_case): slug
? Field type: string
? Field length/size: 100
? Required field? Yes
? Unique field? Yes

? Add a custom field? Yes
? Field name (snake_case): description
? Field type: text
? Required field? No
? Unique field? No

? Add a custom field? No
```

#### Model 4: Comment
```
? Add another model? Yes

? Model name (PascalCase): Comment
? Model description: Post comment

? Add a custom field? Yes
? Field name (snake_case): content
? Field type: text
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): author_id
? Field type: uuid
? Is this a foreign key? Yes
? References which model? User
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): post_id
? Field type: uuid
? Is this a foreign key? Yes
? References which model? Post
? Required field? Yes
? Unique field? No

? Add a custom field? Yes
? Field name (snake_case): parent_id
? Field type: uuid
? Is this a foreign key? Yes
? References which model? Comment
? Required field? No
? Unique field? No
? Description: For nested replies

? Add a custom field? No

? Add another model? No
```

Great! Bangstack will create your workflow file at `workflows/my-blog.workflow.yaml`.

## Step 3: Generate Your Blog Code (1 minute)

Now let's generate the complete application code:

```bash
bang generate workflows/my-blog.workflow.yaml --output ./my-blog
```

You'll see progress indicators for each stage:

```
Progress: ████████████████████████████████ 100%

  ✓ Parsing workflow
  ✓ Validating schema
  ✓ Generating frontend (React)
  ✓ Generating backend (Express)
  ✓ Generating database schema (Drizzle)
  ✓ Generating tests
  ✓ Generating Docker configuration
  ✓ Generating GitHub Actions CI/CD

Elapsed: 12s

Summary
All 8 stages completed successfully
Total time: 12s
```

## Step 4: Explore the Generated Code (30 seconds)

Let's see what was created:

```bash
cd my-blog
tree -L 2
```

You'll see:

```
my-blog/
├── frontend/
│   ├── src/
│   │   ├── components/
│   │   │   ├── auth/
│   │   │   ├── posts/
│   │   │   ├── comments/
│   │   │   └── categories/
│   │   ├── pages/
│   │   ├── hooks/
│   │   ├── api/
│   │   └── App.tsx
│   ├── package.json
│   └── tailwind.config.js
├── backend/
│   ├── src/
│   │   ├── routes/
│   │   │   ├── auth.ts
│   │   │   ├── posts.ts
│   │   │   ├── comments.ts
│   │   │   └── categories.ts
│   │   ├── middleware/
│   │   │   └── auth.ts
│   │   ├── utils/
│   │   └── index.ts
│   └── package.json
├── database/
│   ├── schema.ts
│   ├── migrations/
│   └── seed.ts
├── docker-compose.yml
├── .github/
│   └── workflows/
│       └── ci.yml
└── README.md
```

## Step 5: Run Your Blog (1 minute)

### Option A: Using Docker (Recommended)

Start everything with one command:

```bash
docker-compose up
```

This starts:
- PostgreSQL database on port 5432
- Backend API on port 3001
- Frontend on port 3000

### Option B: Manual Setup

**Terminal 1 - Database:**
```bash
docker run -d \
  --name blog-db \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=blog \
  -p 5432:5432 \
  postgres:15
```

**Terminal 2 - Backend:**
```bash
cd backend
npm install
npm run migrate  # Run database migrations
npm run seed     # Add sample data
npm run dev      # Start backend server
```

**Terminal 3 - Frontend:**
```bash
cd frontend
npm install
npm start        # Start frontend dev server
```

## Step 6: Use Your Blog! (30 seconds)

Open your browser to `http://localhost:3000`

### Try These Features:

1. **Sign Up**: Create a new account
   - Click "Sign Up" in the top right
   - Enter email, username, and password
   - You're automatically logged in!

2. **Create a Post**:
   - Click "New Post"
   - Enter title: "My First Blog Post"
   - Write some content
   - Select a category
   - Click "Publish"

3. **Add a Comment**:
   - Open your post
   - Scroll to comments section
   - Write a comment
   - Submit!

4. **Browse Categories**:
   - Click "Categories" in the navigation
   - See posts organized by category

## What You Got

### Frontend Features ✨
- Modern React UI with TypeScript
- Tailwind CSS styling (fully responsive)
- Authentication (login, signup, logout)
- Post management (create, edit, delete, publish)
- Comment system with nested replies
- Category filtering
- User profiles
- Form validation
- Error handling
- Loading states

### Backend Features 🚀
- RESTful API with Express
- JWT authentication with refresh tokens
- CRUD endpoints for all models
- Password hashing with bcrypt
- Request validation
- Error handling middleware
- CORS configuration
- Rate limiting
- Security headers

### Database Features 💾
- Type-safe Drizzle ORM
- PostgreSQL schema with:
  - Users table with unique constraints
  - Posts table with status enum
  - Categories table
  - Comments table with self-referencing foreign key
  - Proper indexes for performance
  - Timestamps on all tables
- Database migrations
- Seed data for development

### DevOps Features 🛠️
- Docker Compose for local development
- GitHub Actions CI/CD pipeline
- Automated tests on every push
- Environment configuration
- Hot reloading for development
- Production-ready builds

### Test Coverage 🧪
- Frontend component tests (React Testing Library)
- Backend API tests (Supertest)
- E2E tests (Playwright)
- Test database setup

## Next Steps

### 1. Customize Your Blog

Edit the generated code to match your brand:

**Update colors** (`frontend/tailwind.config.js`):
```js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: '#3b82f6',    // Change to your brand color
        secondary: '#8b5cf6',
      },
    },
  },
};
```

**Add your logo** (`frontend/src/components/Header.tsx`):
```tsx
<img src="/logo.svg" alt="My Blog" className="h-8" />
```

### 2. Add More Features

Want to add image uploads? Edit your workflow and regenerate:

```bash
# Edit workflows/my-blog.workflow.yaml
# Add image_url field to Post model
bang generate workflows/my-blog.workflow.yaml --output ./my-blog
```

Bangstack will update only the changed files!

### 3. Deploy to Production

Your blog is production-ready! Deploy to:

- **Vercel** (frontend) + **Railway** (backend + database)
- **Netlify** (frontend) + **Render** (backend + database)
- **AWS** (ECS + RDS)
- **Digital Ocean** (App Platform)

All deployment configurations are included in the generated code.

### 4. Learn More

- [Add Authentication Tutorial](./ADD-AUTHENTICATION.md)
- [Workflow Schema Reference](../EXTENDED-SCHEMA-GUIDE.md)
- [Custom Generators Guide](./CUSTOM-GENERATORS.md)
- [Deployment Guide](../DEPLOYMENT.md)

## Troubleshooting

### Database Connection Error

If you see "Connection refused" errors:

```bash
# Check if PostgreSQL is running
docker ps

# If not, start it:
docker-compose up -d postgres
```

### Port Already in Use

If port 3000 or 3001 is busy:

```bash
# Frontend: Edit frontend/.env
VITE_PORT=3002

# Backend: Edit backend/.env
PORT=3003
```

### Module Not Found

If you see import errors:

```bash
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
```

## Understanding What Happened

In just 5 minutes, Bangstack:

1. **Parsed your workflow** - Understood your requirements from the interactive prompts
2. **Validated the schema** - Checked for errors and inconsistencies
3. **Generated 50+ files** including:
   - React components for each feature
   - Express API routes with validation
   - Drizzle database schema and migrations
   - TypeScript types for full type safety
   - Tests for all layers
   - Docker configuration
   - CI/CD pipelines
4. **Ensured consistency** - All files reference the same models and types
5. **Added best practices** - Security, error handling, and performance optimizations

## What Makes This Special?

### Traditional Development:
- 2-3 days to set up the project structure
- 1 week to build authentication
- 1 week to build the blog features
- 2-3 days for tests
- 1 day for Docker/CI setup
- **Total: 2-3 weeks**

### With Bangstack:
- 5 minutes total
- Full type safety
- Production-ready code
- Tests included
- DevOps configured
- **Total: 5 minutes**

### And When Requirements Change?

**Traditional**: Manually update dozens of files, fix type errors, update tests, update docs

**With Bangstack**: Update your workflow YAML, regenerate, done!

## Real-World Example

Let's say your stakeholders want to add post ratings. With Bangstack:

1. Edit `workflows/my-blog.workflow.yaml`
2. Add to Post model:
```yaml
- name: rating
  type: integer
  validation:
    min: 1
    max: 5
```
3. Regenerate:
```bash
bang generate workflows/my-blog.workflow.yaml --output ./my-blog
```

Bangstack updates:
- Database schema with new column
- TypeScript types
- API endpoints with validation
- Frontend forms and displays
- Tests for new field

**Time: 30 seconds**

## Conclusion

You just built a complete, production-ready blog application in 5 minutes!

The generated code is:
- ✅ Type-safe end-to-end
- ✅ Following best practices
- ✅ Fully tested
- ✅ Production-ready
- ✅ Easy to customize
- ✅ Well-documented

**What's next?**
- Try the [Authentication Tutorial](./ADD-AUTHENTICATION.md) to learn how to customize auth
- Read the [Workflow Best Practices](../WORKFLOW-BEST-PRACTICES.md) guide
- Explore [Custom Generators](./CUSTOM-GENERATORS.md) to extend Bangstack
- Join our [Discord community](https://discord.gg/bangstack)

Happy coding! 🚀

---

**Questions or issues?** Open an issue on [GitHub](https://github.com/mogullabs/bangstack/issues)
