On this page28 sections
- Introduction
- Why Migrate from Vercel?
- The Decision Matrix
- The Redesign: From Next.js to Vite + React
- Previous Stack (Vercel)
- New Stack (Cloudflare)
- Why the Stack Change?
- Migration Steps
- Step 1: Project Setup
- Step 2: Configure Vite for Production
- Step 3: Content Migration
- Step 4: Backend with Hono.js on Cloudflare Workers
- Step 5: Database Migration to Cloudflare D1
- Step 6: Cloudflare Pages Configuration
- Performance Improvements
- Lighthouse Scores Comparison
- Bundle Size Optimization
- Image Optimization
- Design Improvements
- 1. Typography Enhancement
- 2. Dark Mode Implementation
- 3. Animation System with Framer Motion
- Challenges and Solutions
- Challenge 1: Client-Side Routing on Static Hosting
- Challenge 2: Environment Variables
- Challenge 3: RSS Feed Generation
- Lessons Learned
- Conclusion
Introduction
After running my portfolio website on Vercel for over a year, I decided it was time for a major overhaul. This wasn’t just a simple hosting change - it was a complete reimagining of the architecture, design, and technology stack. In this article, I’ll walk you through the entire migration process from Vercel to Cloudflare, the redesign decisions, and the technical challenges I encountered.
Why Migrate from Vercel?
Vercel has been an excellent platform for hosting my Next.js applications. However, several factors led me to consider Cloudflare:
| Factor | Vercel | Cloudflare |
|---|---|---|
| Edge Network | ~18 compute regions | 300+ cities worldwide |
| Pricing Model | Function invocations | Generous free tier |
| DNS Management | Limited | Full-featured |
| Additional Services | Focused on deployment | Workers, R2, D1, KV, etc. |
| Bandwidth | 100GB free | Unlimited |
The Decision Matrix
interface HostingPlatform {
name: string;
edgeLocations: number;
freeTierBandwidth: string;
serverlessFunctions: boolean;
additionalServices: string[];
costAtScale: 'low' | 'medium' | 'high';
}
const platforms: HostingPlatform[] = [
{
name: 'Vercel',
edgeLocations: 20,
freeTierBandwidth: '100GB',
serverlessFunctions: true,
additionalServices: ['Edge Config', 'KV', 'Postgres'],
costAtScale: 'medium',
},
{
name: 'Cloudflare',
edgeLocations: 300,
freeTierBandwidth: 'Unlimited',
serverlessFunctions: true,
additionalServices: ['Workers', 'R2', 'D1', 'KV', 'Pages', 'Images'],
costAtScale: 'low',
},
];The Redesign: From Next.js to Vite + React
The migration wasn’t just about changing hosts - it was an opportunity to rethink the entire architecture.
Previous Stack (Vercel)
- Next.js 14 (Pages Router)
- Server-Side Rendering (SSR)
- Tailwind CSS
- Vercel Analytics
- Static + Dynamic hybrid
New Stack (Cloudflare)
- Vite + React 18
- Static Site Generation (SSG)
- Tailwind CSS 4 (alpha - the new Vite plugin was worth the risk on a personal site)
- Hono.js backend
- Cloudflare Pages + Workers
Why the Stack Change?
// Old approach: Next.js with heavy SSR
// pages/blog/[slug].tsx
export async function getServerSideProps({ params }) {
const post = await fetchPost(params.slug);
return { props: { post } };
}
// New approach: Static generation with client-side hydration
// Vite + React - Build-time generation
const posts = await import('./data/posts.ts');
// Posts are pre-compiled at build timeThe key insight was that my content doesn’t change frequently. A blog and portfolio site can be fully static, with dynamic features handled by edge workers when needed.
Migration Steps
Step 1: Project Setup
# Create new Vite project
npm create vite@latest imaji-web-vite -- --template react-ts
# Install dependencies
cd imaji-web-vite
npm install tailwindcss@next @tailwindcss/vite@next framer-motion # v4 is still alpha, so it lives on the @next tag
npm install react-router-dom react-markdown remark-gfm
npm install -D @types/nodeStep 2: Configure Vite for Production
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { resolve } from 'path';
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': resolve(__dirname, './src'),
'@components': resolve(__dirname, './src/components'),
'@lib': resolve(__dirname, './src/lib'),
},
},
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom', 'react-router-dom'],
animations: ['framer-motion'],
markdown: ['react-markdown', 'remark-gfm'],
},
},
},
},
});Step 3: Content Migration
One of the biggest challenges was migrating blog posts from Next.js’s MDX setup to pure Markdown with front matter parsing:
// scripts/build-content.ts
import matter from 'gray-matter';
import { readFileSync, readdirSync, writeFileSync } from 'fs';
import { join } from 'path';
interface PostFrontMatter {
title: string;
slug: string;
excerpt: string;
publishedAt: string;
tags: string[];
readingTime: number;
}
function buildPosts(): void {
const postsDir = join(process.cwd(), 'content/posts');
const files = readdirSync(postsDir).filter(f => f.endsWith('.md'));
const posts = files.map(filename => {
const filePath = join(postsDir, filename);
const fileContent = readFileSync(filePath, 'utf-8');
const { data, content } = matter(fileContent);
return {
type: 'post',
slug: data.slug,
title: data.title,
excerpt: data.excerpt,
publishedAt: data.publishedAt,
tags: data.tags || [],
readingTimeMinutes: calculateReadingTime(content),
content,
data,
};
});
// Sort by date
posts.sort((a, b) =>
new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime()
);
// Write to TypeScript file
writeFileSync(
join(process.cwd(), 'src/data/posts.ts'),
`// Auto-generated - Do not edit manually
export const posts = ${JSON.stringify(posts, null, 2)};`
);
console.log(`Built ${posts.length} posts`);
}
function calculateReadingTime(content: string): number {
const wordsPerMinute = 200;
const words = content.split(/\s+/).length;
return Math.ceil(words / wordsPerMinute);
}
buildPosts();Step 4: Backend with Hono.js on Cloudflare Workers
// backend/src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { articles } from './routes/articles';
import { projects } from './routes/projects';
import { contact } from './routes/contact';
type Bindings = {
DB: D1Database;
ENVIRONMENT: string;
};
const app = new Hono<{ Bindings: Bindings }>();
// Middleware
app.use('*', logger());
app.use('*', cors({
origin: ['https://imaji-web.pages.dev', 'http://localhost:5173'],
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
}));
// Routes
app.route('/api/articles', articles);
app.route('/api/projects', projects);
app.route('/api/contact', contact);
// Health check
app.get('/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));
export default app;Step 5: Database Migration to Cloudflare D1
-- backend/src/db/schema.sql
CREATE TABLE IF NOT EXISTS articles (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
slug TEXT UNIQUE NOT NULL,
excerpt TEXT,
content TEXT,
cover_image TEXT,
category TEXT,
tags TEXT,
reading_time INTEGER,
featured INTEGER DEFAULT 0,
draft INTEGER DEFAULT 0,
published_at TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
location TEXT,
start_date TEXT,
end_date TEXT,
role TEXT,
summary TEXT,
skills TEXT,
github_url TEXT,
live_url TEXT,
sort_order INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_articles_slug ON articles(slug);
CREATE INDEX idx_articles_category ON articles(category);
CREATE INDEX idx_projects_category ON projects(category);Step 6: Cloudflare Pages Configuration
# wrangler.toml
name = "imaji-web"
compatibility_date = "2024-01-01"
pages_build_output_dir = "./frontend/dist"
[[d1_databases]]
binding = "DB"
database_name = "imaji-db"
database_id = "your-database-id"
[vars]
ENVIRONMENT = "production"Performance Improvements
The migration resulted in significant performance gains:
Lighthouse Scores Comparison
| Metric | Before (Vercel) | After (Cloudflare) |
|---|---|---|
| Performance | 92 | 100 |
| Accessibility | 95 | 100 |
| Best Practices | 100 | 100 |
| SEO | 100 | 100 |
| First Contentful Paint | 1.2s | 0.4s |
| Largest Contentful Paint | 2.1s | 0.8s |
| Total Blocking Time | 150ms | 0ms |
Bundle Size Optimization
// Before: Next.js bundle
// Total: ~450KB (gzipped)
// After: Vite + React
// Vendor chunk: 85KB
// App chunk: 45KB
// Total: ~130KB (gzipped)
// 70% reduction in initial bundle size!Image Optimization
// Using Cloudflare Images for automatic optimization
function getOptimizedImageUrl(
imageId: string,
options: { width?: number; quality?: number; format?: 'webp' | 'avif' }
): string {
const opts: string[] = [];
if (options.width) opts.push(`width=${options.width}`);
if (options.quality) opts.push(`quality=${options.quality}`);
if (options.format) opts.push(`format=${options.format}`);
return `https://imagedelivery.net/${accountId}/${imageId}/${opts.join(',')}`;
}
// Usage in React component
<img
src={getOptimizedImageUrl(post.coverImage, {
width: 800,
quality: 85,
format: 'webp'
})}
alt={post.title}
loading="lazy"
/>Design Improvements
The redesign focused on three key areas:
1. Typography Enhancement
/* New typography system */
:root {
--font-sans: 'Inter Variable', system-ui, sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--font-display: 'Cabinet Grotesk', var(--font-sans);
}
/* Responsive typography scale */
.prose {
font-size: clamp(1rem, 0.95rem + 0.25vw, 1.125rem);
line-height: 1.75;
}
.heading-1 {
font-size: clamp(2rem, 1.5rem + 2.5vw, 3.5rem);
font-weight: 700;
letter-spacing: -0.02em;
}2. Dark Mode Implementation
// Theme toggle with system preference detection
function useTheme() {
const [theme, setTheme] = useState<'light' | 'dark'>(() => {
if (typeof window === 'undefined') return 'light';
const stored = localStorage.getItem('theme');
if (stored === 'light' || stored === 'dark') return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
});
useEffect(() => {
const root = document.documentElement;
root.classList.remove('light', 'dark');
root.classList.add(theme);
localStorage.setItem('theme', theme);
}, [theme]);
const toggle = () => setTheme(t => (t === 'light' ? 'dark' : 'light'));
return { theme, toggle };
}3. Animation System with Framer Motion
// Reusable animation variants
const fadeInUp = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 },
};
const staggerContainer = {
animate: {
transition: {
staggerChildren: 0.1,
},
},
};
// Usage in components
<motion.div
variants={staggerContainer}
initial="initial"
animate="animate"
>
{posts.map(post => (
<motion.article key={post.slug} variants={fadeInUp}>
<PostCard post={post} />
</motion.article>
))}
</motion.div>Challenges and Solutions
Challenge 1: Client-Side Routing on Static Hosting
Cloudflare Pages serves static files, but React Router needs to handle all routes:
// _redirects file for Cloudflare Pages
/* /index.html 200
// Or using _routes.json
{
"version": 1,
"include": ["/*"],
"exclude": ["/api/*", "/images/*", "/fonts/*"]
}Challenge 2: Environment Variables
// Different approach for Vite vs Next.js
// Next.js: process.env.NEXT_PUBLIC_*
// Vite: import.meta.env.VITE_*
// vite.config.ts
export default defineConfig({
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
},
});
// Usage
const apiUrl = import.meta.env.VITE_API_URL || 'https://imaji-web.pages.dev/api';Challenge 3: RSS Feed Generation
// scripts/generate-rss.ts
import { writeFileSync } from 'fs';
import { posts } from '../src/data/posts';
function generateRSSFeed(): void {
const siteUrl = 'https://imaji-web.pages.dev';
const rss = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Imaji - Blog</title>
<link>${siteUrl}</link>
<description>Articles about software engineering and civil engineering</description>
<atom:link href="${siteUrl}/rss.xml" rel="self" type="application/rss+xml"/>
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
${posts
.filter(p => !p.draft)
.map(post => `
<item>
<title><![CDATA[${post.title}]]></title>
<link>${siteUrl}/blog/${post.slug}</link>
<guid isPermaLink="true">${siteUrl}/blog/${post.slug}</guid>
<pubDate>${new Date(post.publishedAt).toUTCString()}</pubDate>
<description><![CDATA[${post.excerpt}]]></description>
</item>`)
.join('')}
</channel>
</rss>`;
writeFileSync('dist/rss.xml', rss);
console.log('RSS feed generated');
}
generateRSSFeed();Lessons Learned
-
Static is often enough - Don’t over-engineer. If your content doesn’t change every request, static generation is simpler and faster.
-
Edge computing is powerful - Cloudflare Workers allow you to add dynamic features at the edge without sacrificing static site benefits.
-
Bundle size matters - Moving from Next.js to Vite reduced my bundle by 70%. Every kilobyte counts for performance.
-
Migration is opportunity - A platform change is the perfect time to reconsider your entire architecture.
-
Document everything - This article exists because I documented the process as I went.
Conclusion
Migrating from Vercel to Cloudflare was more than a hosting change - it was a complete reimagining of how my website should work. The result is a faster, more maintainable, and more cost-effective solution.
If you’re considering a similar migration, I hope this guide helps you navigate the process. The key is to view it not as a chore, but as an opportunity to build something better.
Tech Stack Summary:
- Frontend: Vite + React 18 + TypeScript + Tailwind CSS 4 (alpha)
- Backend: Hono.js on Cloudflare Workers
- Database: Cloudflare D1 (SQLite)
- Hosting: Cloudflare Pages
- Domain: imaji-web.pages.dev (a custom domain came later)
Resources: