TaleByYou
AI-powered ecommerce platform for creating personalized children's storybooks with custom characters and print-on-demand delivery

Overview
This is my first real product with actual paying customers. The idea: parents can create custom storybooks where their kid is the main character. Not just inserting a name - the child actually appears in every illustration, looking like themselves.
The hardest part was getting AI to generate consistent characters across 20+ pages. Tried a bunch of different approaches before landing on Leonardo AI's Character Reference feature. Now you upload one photo and the AI uses it as reference for every page.
- Upload one photo → AI keeps the character looking the same across all pages
- Order physical hardcover books or just get the digital PDF
- No account needed to start - create as guest, register when ready
- Full ecommerce: PayPal checkout, print-on-demand via Lulu, automated fulfillment
Built for parents, grandparents, anyone buying gifts for kids ages 2-10. The books actually get printed and shipped worldwide.
Tech Stack
Core Framework
- Next.js 15 with App Router and React for modern server/client architecture
- TypeScript in strict mode for complete type safety
- Tailwind CSS 4 with custom animations and design system
- shadcn/ui for accessible components
- Framer Motion for smooth animations and transitions
Interactive Features
- React Hook Form + Zod for validated form handling
- React Image Crop & React Easy Crop for photo editing
- Embla Carousel, Swiper, React Slick for galleries
- React Pageflip for interactive book preview
- Zustand for client state management
UI Components
- Lucide React for consistent iconography
- Custom shadcn/ui components built on Radix primitives
- Responsive design with mobile-first approach
Architecture
The application follows a clean layered architecture with clear separation of concerns, making it maintainable and scalable.
Route Organization
app/├── (main)/ # Public pages│ ├── page.tsx # Homepage│ ├── library/ # Book templates│ │ ├── customize/ # Personalization flow│ │ └── preview/ # Book editor│ ├── blog/ # Content marketing│ └── contact/ # Support├── (auth)/ # Clerk authentication│ ├── sign-in/│ └── sign-up/├── (admin)/ # Admin dashboard│ ├── books/ # Manage all books│ ├── orders/ # Order fulfillment│ ├── templates/ # Template management│ └── pricing/ # Cost configuration└── api/└── webhooks/ # Third-party webhooks├── clerk/ # User sync├── leonardo/ # Image completion└── lulu/ # Print status
Database Schema
Core Features
Book Template Library
Browse pre-made book templates with rich metadata including genres, age ranges, and preview pages. Each template is professionally crafted with engaging storylines designed for specific age groups (2-4, 5-7, 8-10 years old).
Template Categories:
- Adventure stories (dinosaurs, space, ocean exploration)
- Educational books (construction, animals, science)
- Fantasy tales (unicorns, dragons, magical worlds)
- Everyday heroes (firefighters, doctors, teachers)

Library page, templates with client side filtering

Featured templates
Character Customization
Create a unique character that looks exactly like the child:
Physical Customization:
- Hair color and style (10+ options)
- Eye color (brown, blue, green, hazel)
- Skin tone (6+ options)
- Accessories (glasses, freckles)
Personal Details:
- Child's name (appears throughout story)
- Age and gender
- Optional photo upload for AI reference

Character customization for consistency

Good and Bad examples
AI Character Consistency
The breakthrough feature that makes TaleByYou special. Using Leonardo AI's Character Reference ControlNet:
- Upload one photo of the child
- AI uses it as reference for ALL illustrations
- Same child appears consistently across 20+ pages
- No manual editing or touch-ups needed
Technical Implementation:
- Character Reference preprocessor (ID 133)
- 3 image variations generated per page
- User selects favorite from options
- 20-60 second generation time per batch

Forest explorer template

Forest explorer template

Forest explorer template

Forest explorer template
Interactive Book Editor
Full-featured preview and editing interface with:
Visual Editor:
- Flip-book style preview (react-pageflip)
- View book as it will appear in print
- Smooth page-turning animations
Content Editing:
- Edit text on any page
- Customize dedications (cover and first page)
- Select from 3 AI-generated image variations per page
Image Regeneration:
- Not happy with an image? Regenerate with custom prompt
- Keeps character consistency
- Unlimited regenerations until perfect
Status Tracking:
- Mark book as "ready for printing" when complete
- Save progress and return later
- Auto-save prevents data loss

Edit title, add cover dedication

Can edit text content
Flexible E-commerce
Two product types to fit different needs:
Digital Only (EBOOK):
- Instant delivery after payment
- PDF download (optimized for printing at home)
- EPUB format (for e-readers)
- $19.99 base price
Physical + Digital Bundle (BOOK):
- Premium hardcover book (8.5" x 11")
- Case wrap binding (professional quality)
- Full-color interior on 200GSM paper
- Ships worldwide via Lulu
- Includes PDF and EPUB downloads
- $34.99 + shipping
Dynamic Pricing:
- Real-time printing cost calculation via Lulu API
- 5 shipping speed options (Mail to Express)
- AI generation costs included
- Transparent pricing breakdown
Guest Checkout
No account required to start creating books:
- Create up to 2 books as a guest
- Session stored in encrypted cookie (30-day expiry)
- Enter email only at checkout
- Can register later to claim books
Benefits:
- Reduces friction for first-time users
- Better conversion rates
- Gifts can be created without recipient needing account
Automated Fulfillment
End-to-end automation from order to delivery:
For Digital Orders:
- Payment confirmed via PayPal webhook
- E-books generated on-demand (PDF + EPUB)
- Uploaded to S3 with 7-day expiration
- Download links emailed to customer
- Customer downloads within 7 days
For Physical Orders:
- Payment confirmed
- PDFs generated (interior + cover wraparound)
- Submitted to Lulu for printing
- Status updates via webhook (IN_PRODUCTION → SHIPPED)
- Tracking number emailed to customer
- E-books also included in email
Email Notifications:
- Order confirmation
- Payment receipt
- E-book download links
- Print job started
- Shipment tracking
Admin Dashboard
Complete backend management system:

Book Management:
- View all user books
- Monitor generation status
- Send books to printer
- Handle custom requests

Manage all book

Edit text content , prompts, image, regenerate images
Order Fulfillment:
- Order status tracking
- Payment verification
- Manual print job submission
- Shipping updates

Template Management:
- Create/edit book templates
- Upload cover images and prompts
- Manage page content
- Genre assignment

Manage all templates

Create and edit template
Pricing Configuration:
- Set profit margins
- Configure shipping markups
- Monitor AI credit costs
- Cost breakdown analytics

AI Image Generation Pipeline
Print-on-Demand Workflow
Technical Challenges & Solutions
Challenge 1: Getting Characters to Look the Same
Started with Stable Diffusion and Midjourney. The character looked completely different on every page - different hair, different face, sometimes different race. Parents would never buy books like that.
Spent weeks testing different approaches. Finally found Leonardo AI's Character Reference feature (ControlNet preprocessor 133). You upload one photo and it uses that as reference for every single generation. The AI actually maintains the same facial features, hair style, everything.
Now the character looks consistent across all 20+ pages. Parents send me photos of their kids recognizing themselves in the books. Way less regenerations needed.
Challenge 2: Nobody Wanted to Sign Up First
Had a mandatory registration screen. 60% of people bounced immediately. Makes sense - who wants to create an account before knowing if the product is even good?
Built a guest session system with encrypted cookies. You can create up to 2 books without any account. Session lasts 30 days. If you order, you get an option to register and claim your books. Prevents abuse but lets people try it first.
Conversion went up 35%. People make their first book, see that it actually works, then buy. Most register after they see the final product.
Challenge 3: Lulu's PDF Requirements Are Brutal
Lulu rejected 40% of my PDFs. They need exact dimensions with bleed margins, spine width that changes based on page count, safety zones, specific color profiles. The error messages were useless - just 'PDF validation failed.'
Used their API to calculate cover dimensions dynamically. Built a PDF generator with PDFKit where I control every pixel. Added my own validation before sending to Lulu. Tested with books of different lengths until I got it right.
99.8% success rate now. Only fails if someone uploads a corrupted image. Saves me hours of back-and-forth with customers about failed print jobs.
Challenge 4: Pricing Is Complicated
The total price depends on: printing cost (changes with page count), shipping (5 options, varies by country), AI generation costs, and my profit margin. All of this needs to calculate in real-time before someone checks out.
Chained API calls in a service layer: get printing cost from Lulu, get shipping for their location, sum up AI costs from my database, apply markup, return breakdown. Cache the result so I'm not hammering Lulu's API for every price check.
Instant pricing. Customers see the breakdown and trust it. I can adjust margins without updating prices manually.
Challenge 5: Waiting for AI Sucks
Each image generation takes 20-60 seconds. Started with a loading spinner that blocked the whole page. People would close the tab, lose their progress, and email me confused.
Switched to webhooks. Start the generation, let people close the page. Leonardo pings me when it's done, I send them an email with a link back. If they stay on the page, they see progress. Either way, nothing gets lost.
Way better UX. People start the generation and go do something else. Come back when they get the email. No more lost work.
Challenge 6: PDF Storage Was Getting Expensive
Storing PDFs permanently for every order. 100 orders = 200 files at 5MB each = 1GB monthly. Costs kept climbing and most people download once then never again.
Generate PDFs on-demand when someone orders. Upload to S3 with 7-day expiration. They get a download link that works for a week. If they lose it, they can request a new one (charge a small fee to prevent abuse).
Cut storage costs by 90%. People download within a day anyway. Less than 2% ask for regeneration.
Challenge 7: Image Selection Was Tedious
Users pick from 3 AI variations per page, across 20+ pages. My first version: one page at a time. Took forever. Thumbnails were too small to actually see details.
Built a grid showing all pages. Click for full-size lightbox. Arrow keys to navigate. Checkmark shows what's selected. Added bulk actions to auto-select for all pages. Keyboard shortcuts for people who want to go fast.
Selection time dropped from 10 minutes to 2. People actually enjoy this part now.
Performance Optimizations
Image Optimization
Next.js Image component with WebP-only format (removed AVIF to reduce transformations). 31-day cache TTL. Limited quality options [50, 75]. Optimized device sizes for responsive loading.
Lazy Loading
React lazy() for below-the-fold components. Suspense boundaries with skeleton loading states. Code splitting for admin routes. Reduces initial bundle by 40%.
Database Optimization
Prisma Accelerate for connection pooling. Indexed foreign keys on high-traffic queries. Selective field selection (only fetch what's needed). Reduced average query time from 150ms to 40ms.
State Management
Zustand for lightweight client state (modals, UI toggles). React Query for server state with automatic caching. Avoids prop drilling and unnecessary re-renders.
Server Components
Next.js 15 App Router with Server Components by default. Client Components only where interactivity is needed. Reduces JavaScript sent to browser by 60%.
Caching Strategy
Static pages: Generated at build time. Dynamic pages: ISR with 60-second revalidation.
Security Measures
Testing Strategy
The project includes unit tests for critical business logic, ensuring reliability in production.
Test Files:
src/actions/__tests__/order-actions.test.ts
- Order creation and paymentsrc/services/book/book-creation-service.test.ts
- Book personalization logicsrc/services/image/image-generation-service.test.ts
- AI generation workflows
Testing Tools:
- Jest with ts-jest for TypeScript support
- Mocking of external APIs (Leonardo, Lulu, PayPal)
- Database mocking with Prisma's test client
Deployment Architecture
Environment Configuration:
- Auto-switching between Lulu sandbox/production based on NODE_ENV
- Centralized config in
src/lib/config.ts
- Type-safe environment variables with validation at startup