An open API service indexing awesome lists of open source software.

https://github.com/guerrerocarlos/fullstack-cloudflare-template

A modern fullstack application template built with React, Cloudflare Workers, and Prisma D1. Features TypeScript, Vite, UnoCSS, and a dynamic REST API ready for rapid development.
https://github.com/guerrerocarlos/fullstack-cloudflare-template

cloudflare fullstack hono typescript workers

Last synced: 5 months ago
JSON representation

A modern fullstack application template built with React, Cloudflare Workers, and Prisma D1. Features TypeScript, Vite, UnoCSS, and a dynamic REST API ready for rapid development.

Awesome Lists containing this project

README

          

# Fullstack Cloudflare Template

A comprehensive fullstack application template built with modern web technologies. This project provides a solid foundation for building scalable web applications using React on the frontend and Cloudflare Workers on the backend, with Prisma ORM and Cloudflare D1 for data management.

## 🚀 Features

### User Management
- **Authentication**: Secure user login and session management
- **Role-based Access**: Permissions system for different user types
- **Profile Management**: User information and preferences

### Data Management
- **CRUD Operations**: Create, read, update, and delete data entities
- **Real-time Updates**: Live data synchronization
- **Audit Trail**: Complete history of all data changes

### API Integration
- **REST-like Endpoints**: Dynamic API with automatic ORM integration
- **Cross-origin Support**: CORS-enabled for web clients
- **Error Handling**: Comprehensive error management
- **Type Safety**: Full TypeScript support throughout

## 🛠 Tech Stack

### Frontend
- **React 19**: Modern React with hooks and concurrent features
- **Vite**: Fast build tool and development server
- **Zustand**: Lightweight state management
- **UnoCSS**: Utility-first CSS framework
- **TypeScript**: Type-safe development

### Backend
- **Cloudflare Workers**: Serverless runtime for API endpoints
- **Hono**: Fast, lightweight web framework
- **Prisma ORM**: Type-safe database operations
- **Cloudflare D1**: SQLite-compatible database
- **Prisma D1 Adapter**: Seamless D1 integration

### Development Tools
- **Wrangler**: Cloudflare's development tool
- **ESLint**: Code linting and formatting
- **TypeScript**: Type checking
- **PNPM**: Fast package manager

## 📋 Prerequisites

- **Node.js**: Version 18 or higher
- **PNPM**: Package manager
- **Cloudflare Account**: For D1 database and Workers deployment
- **Wrangler CLI**: Cloudflare's development tool

```bash
# Install PNPM
npm install -g pnpm

# Install Wrangler
npm install -g wrangler
```

## 🚀 Installation & Setup

### 1. Clone the Repository
```bash
git clone
cd fullstack-cloudflare-template
```

### 2. Install Dependencies
```bash
pnpm install
```

### 3. Environment Setup
The project uses Cloudflare's environment variables. No additional `.env` files are needed as bindings are configured in `wrangler.json`.

### 4. Database Setup

#### Create D1 Database
```bash
npx wrangler d1 create my-app-db
```
This will create a D1 database and automatically add the binding to your `wrangler.json`.

#### Apply Database Schema
```bash
# Generate Prisma client
npx prisma generate

# Create and apply migration
npx wrangler d1 migrations create my-app-db init_schema
npx wrangler d1 migrations apply my-app-db --local
```

### 5. Development Server
```bash
# Start the Vite development server
pnpm run dev
```
The application will be available at `http://localhost:5173/`

## 🗄 Database Schema

### User Model
```prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```

### Post Model
```prisma
model Post {
id Int @id @default(autoincrement())
title String
content String?
authorId Int
author User @relation(fields: [authorId], references: [id])
comments Comment[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```

### Comment Model
```prisma
model Comment {
id Int @id @default(autoincrement())
content String
postId Int
post Post @relation(fields: [postId], references: [id])
authorId Int
author User @relation(fields: [authorId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```

## 📡 API Documentation

The API uses a dynamic routing system: `/api/{model}/{method}`

### Supported Models
- `user` - User management
- `post` - Content management
- `comment` - Comment system

### Supported Methods
- `findMany` - Get multiple records
- `findUnique` - Get single record by unique field
- `findFirst` - Get first matching record
- `create` - Create new record
- `createMany` - Create multiple records
- `update` - Update existing record
- `updateMany` - Update multiple records
- `upsert` - Create or update record
- `delete` - Delete record
- `deleteMany` - Delete multiple records
- `count` - Count records
- `aggregate` - Aggregate data
- `groupBy` - Group records

### Example API Calls

#### Get All Posts
```bash
GET /api/post/findMany
```

#### Create New User
```bash
POST /api/user/create
Content-Type: application/json

{
"email": "john@example.com",
"name": "John Doe"
}
```

#### Create New Post
```bash
POST /api/post/create
Content-Type: application/json

{
"title": "My First Post",
"content": "This is the content of my post",
"authorId": 1
}
```

### Error Handling
All API errors return a standardized JSON response:
```json
{
"success": false,
"error": "Human-readable error message"
}
```

## 🏗 Development

### Project Structure
```
fullstack-cloudflare-template/
├── src/
│ ├── react-app/ # React frontend
│ │ ├── components/ # Reusable components
│ │ ├── pages/ # Page components
│ │ └── stores/ # Zustand stores
│ ├── worker/ # Cloudflare Worker API
│ │ └── index.ts # Main worker file
│ └── generated/ # Prisma client
├── prisma/
│ └── schema.prisma # Database schema
├── migrations/ # D1 migrations
├── public/ # Static assets
└── wrangler.json # Cloudflare config
```

### Available Scripts
```bash
# Development
pnpm run dev # Start Vite dev server
pnpm run build # Build for production
pnpm run preview # Preview production build

# Database
pnpm run cf-typegen # Generate Cloudflare types

# Code Quality
pnpm run lint # Run ESLint
pnpm run check # TypeScript type check
```

### Adding New Features
1. **Database Changes**: Update `prisma/schema.prisma`
2. **Regenerate Client**: Run `npx prisma generate`
3. **Create Migration**: `npx wrangler d1 migrations create`
4. **Apply Migration**: `npx wrangler d1 migrations apply`

## 🚀 Deployment

### Local Testing
```bash
# Test with local D1
npx wrangler dev
```

### Production Deployment
```bash
# Apply migrations to remote D1
npx wrangler d1 migrations apply my-app-db --remote

# Deploy to Cloudflare
npx wrangler deploy
```

### Environment Variables
Configure these in your Cloudflare dashboard or `wrangler.json`:
- `DATABASE_URL`: D1 database connection (handled automatically by binding)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/your-feature`
3. Commit changes: `git commit -am 'Add new feature'`
4. Push to branch: `git push origin feature/your-feature`
5. Submit a pull request

### Code Standards
- Use TypeScript for all new code
- Follow ESLint configuration
- Write comprehensive tests for new features
- Update documentation for API changes

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🆘 Troubleshooting

### Common Issues

**Prisma Client Not Found**
```bash
npx prisma generate
```

**Migration Errors**
```bash
npx wrangler d1 migrations apply my-app-db --local --force
```

**CORS Issues**
Ensure your requests include proper headers or use a proxy in development.

**Database Connection**
Verify your D1 binding in `wrangler.json` matches the database name.

## 📞 Support

For questions or issues:
- Check existing GitHub issues
- Create a new issue with detailed information
- Include error logs and reproduction steps

---

Built with ❤️ using Cloudflare Workers, React, and modern web technologies.