AI Code Generation Guide - Project Bolt Platform
Learn how to generate high-quality code using AI models in Project Bolt. Master automated code generation for components, APIs, and tests.
Code Generation with AI
Learn how to use Project Bolt's AI-powered code generation capabilities to accelerate your development process.
Introduction
AI code generation can help you:
- Write boilerplate code faster
- Generate complex algorithms
- Create test cases automatically
- Build UI components from descriptions
- Convert between programming languages
Basic Code Generation
Component Generation
Generate React components using natural language:
// AI: Create a button component with loading state
const LoadingButton = ({
isLoading,
children,
onClick
}: LoadingButtonProps) => {
return (
<button
className={`btn ${isLoading ? 'loading' : ''}`}
onClick={onClick}
disabled={isLoading}
>
{isLoading ? <Spinner /> : children}
</button>
);
};
API Endpoint Generation
Generate API endpoints with proper error handling:
// AI: Create an API endpoint for user registration
export async function POST(req: Request) {
try {
const { email, password, name } = await req.json();
// Validate input
if (!email || !password || !name) {
return new Response(
JSON.stringify({ error: 'Missing required fields' }),
{ status: 400 }
);
}
// Create user
const user = await db.user.create({
data: {
email,
name,
password: await hashPassword(password),
},
});
return new Response(
JSON.stringify({
message: 'User created successfully',
userId: user.id
}),
{ status: 201 }
);
} catch (error) {
console.error('Registration error:', error);
return new Response(
JSON.stringify({ error: 'Internal server error' }),
{ status: 500 }
);
}
}
Advanced Generation Features
Database Schema Generation
Generate Prisma schema from description:
// AI: Create a blog post schema with categories and tags
model Post {
id String @id @default(cuid())
title String
content String
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
categories Category[]
tags Tag[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Category {
id String @id @default(cuid())
name String @unique
posts Post[]
}
model Tag {
id String @id @default(cuid())
name String @unique
posts Post[]
}
Test Generation
Generate comprehensive test suites:
// AI: Generate tests for authentication middleware
describe('Authentication Middleware', () => {
it('should allow access with valid token', async () => {
const token = generateTestToken({ userId: '123' });
const req = mockRequest({ headers: {
authorization: `Bearer ${token}`
}});
const res = mockResponse();
const next = jest.fn();
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalled();
expect(req.user).toBeDefined();
expect(req.user.id).toBe('123');
});
it('should reject invalid tokens', async () => {
const req = mockRequest({ headers: {
authorization: 'Bearer invalid-token'
}});
const res = mockResponse();
const next = jest.fn();
await authMiddleware(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(next).not.toHaveBeenCalled();
});
});
Best Practices
1. Clear Prompts
Write specific, detailed prompts:
// ❌ Unclear prompt
// AI: Create a form
// ✅ Clear prompt
// AI: Create a user registration form with email, password,
// and name fields, including validation and error handling
2. Iterative Generation
Break down complex generations into steps:
// Step 1: Generate basic structure
// AI: Create base e-commerce product interface
// Step 2: Add specific features
// AI: Add inventory tracking to product interface
// Step 3: Add validation
// AI: Add input validation for product creation
3. Code Review
Always review generated code:
- Check for security issues
- Verify business logic
- Ensure proper error handling
- Test edge cases
Advanced Techniques
Custom Templates
Create templates for consistent generation:
// .boltai/templates/component.ts
export const componentTemplate = `
import React from 'react';
import styles from './${name}.module.css';
interface ${name}Props {
// Props interface
}
export const ${name}: React.FC<${name}Props> = ({}) => {
return (
<div className={styles.container}>
{/* Component content */}
</div>
);
};
`;
Integration with Version Control
Automatically commit generated code:
# Generate and commit component
bolt generate component Button --commit "feat: add Button component"
Troubleshooting
Common generation issues:
Incorrect Generation
# Regenerate with different parameters
bolt generate --retry --temperature 0.7
# Use more specific prompt
bolt generate --prompt "Create a TypeScript React component
for a loading button with spinner animation"
Performance Issues
# Clear generation cache
bolt generate --clear-cache
# Use lightweight model
bolt generate --model fast
Next Steps
- Try generating a complete feature
- Experiment with different prompts
- Create custom templates
- Learn about Smart Debugging
Remember: AI code generation is a powerful tool, but it's important to understand the generated code and ensure it meets your project's requirements and standards.