Back to Projects

TaleByYou

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

9 min read
2331 words
nextjstypescriptreactaiprismapostgresqlecommerceshadcn/uireact queryzustandclerkwebhooksREST API
TaleByYou
TaleByYou

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.

What Makes It Work
  • 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.

20+
Book Templates
3
Images per Page
Custom
Full Customization
7 Days
E-book Access

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

Layered Architecture

The application follows a clean layered architecture with clear separation of concerns, making it maintainable and scalable.

Presentation Layer → Server/Client Components
Application Layer → Server Actions & API Routes
Service Layer → Business Logic (book, image, print, payment services)
Data Access Layer → Prisma ORM + PostgreSQL

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

Library page, templates with client side filtering

Featured templates

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

Character customization for consistency

Featured templates

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
Character on page 1

Forest explorer template

Character on page 2

Forest explorer template

Character on page 3

Forest explorer template

Character on page 4

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
interactive book editor

Edit title, add cover dedication

interactive book editor

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:

  1. Payment confirmed via PayPal webhook
  2. E-books generated on-demand (PDF + EPUB)
  3. Uploaded to S3 with 7-day expiration
  4. Download links emailed to customer
  5. Customer downloads within 7 days

For Physical Orders:

  1. Payment confirmed
  2. PDFs generated (interior + cover wraparound)
  3. Submitted to Lulu for printing
  4. Status updates via webhook (IN_PRODUCTION → SHIPPED)
  5. Tracking number emailed to customer
  6. 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:

Admin Dashboard
Admin Dashboard

Book Management:

  • View all user books
  • Monitor generation status
  • Send books to printer
  • Handle custom requests
Admin Books management

Manage all book

Admin Books Edit

Edit text content , prompts, image, regenerate images

Order Fulfillment:

  • Order status tracking
  • Payment verification
  • Manual print job submission
  • Shipping updates
Order management
View and manage orders

Template Management:

  • Create/edit book templates
  • Upload cover images and prompts
  • Manage page content
  • Genre assignment
Template management

Manage all templates

Template management

Create and edit template

Pricing Configuration:

  • Set profit margins
  • Configure shipping markups
  • Monitor AI credit costs
  • Cost breakdown analytics
Pricing management
Manage prices and discounts

AI Image Generation Pipeline

Technical Challenges & Solutions

Challenge 1: Getting Characters to Look the Same

Problem

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.

Solution

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.

Result

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

Problem

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?

Solution

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.

Result

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

Problem

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.'

Solution

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.

Result

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

Problem

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.

Solution

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.

Result

Instant pricing. Customers see the breakdown and trust it. I can adjust margins without updating prices manually.

Challenge 5: Waiting for AI Sucks

Problem

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.

Solution

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.

Result

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

Problem

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.

Solution

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).

Result

Cut storage costs by 90%. People download within a day anyway. Less than 2% ask for regeneration.

Challenge 7: Image Selection Was Tedious

Problem

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.

Solution

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.

Result

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

Test Coverage

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 payment
  • src/services/book/book-creation-service.test.ts - Book personalization logic
  • src/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

Vercel → Next.js hosting with edge functions
PostgreSQL → Database (Neon)
AWS S3 → File storage (images, PDFs)
Leonardo AI → Image generation
Lulu xPress → Printing & shipping
PayPal → Payment processing
Clerk → Authentication
Webhooks → Status updates from all services

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
TaleByYou | Shalev Asor