implement ssg config for blog posts in project ,

This commit is contained in:
mahdiarghyani
2025-11-10 18:09:18 +03:30
parent d2333d3db2
commit 713bb83981
37 changed files with 5505 additions and 297 deletions
+394
View File
@@ -0,0 +1,394 @@
# Design Document: Blog SSG Optimization
## Overview
این طراحی یک سیستم کامل Static Site Generation برای بلاگ را پیاده‌سازی می‌کند که تمام صفحات بلاگ را در زمان build به صورت استاتیک تولید می‌کند. این رویکرد performance، SEO و قابلیت استقرار را بهبود می‌دهد.
## Architecture
### High-Level Architecture
```
Build Time:
┌─────────────────────────────────────────────────────────┐
│ Nuxt Build Process │
│ │
│ ┌──────────────┐ ┌─────────────────┐ │
│ │ Content │─────▶│ Route │ │
│ │ Discovery │ │ Generator │ │
│ └──────────────┘ └─────────────────┘ │
│ │ │ │
│ │ ▼ │
│ │ ┌─────────────────┐ │
│ │ │ Pre-renderer │ │
│ │ └─────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌─────────────────┐ │
│ │ Sitemap │ │ Static HTML │ │
│ │ Generator │ │ Files │ │
│ └──────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────┘
┌──────────────────┐
│ .output/public │
│ (Static Files) │
└──────────────────┘
```
### Runtime Architecture
```
User Request ──▶ CDN/Static Host ──▶ Pre-rendered HTML
(No Server Required)
```
## Components and Interfaces
### 1. Nitro Prerender Configuration
**Purpose:** پیکربندی Nitro برای pre-rendering خودکار تمام مسیرهای بلاگ
**Location:** `nuxt.config.ts`
**Configuration:**
```typescript
nitro: {
prerender: {
crawlLinks: true,
routes: [
'/',
'/blog',
'/fa/blog'
]
}
}
```
**Key Features:**
- `crawlLinks: true` - خزیدن خودکار لینک‌ها برای کشف مسیرها
- مسیرهای seed برای شروع crawling
- پشتیبانی از چند زبانه (en/fa)
### 2. Dynamic Route Generator Hook
**Purpose:** تولید خودکار لیست تمام مسیرهای بلاگ برای pre-rendering
**Location:** `nuxt.config.ts` یا `server/plugins/prerender.ts`
**Implementation Strategy:**
از Nitro hook `prerender:routes` برای اضافه کردن مسیرهای دینامیک:
```typescript
// server/plugins/prerender.ts
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('prerender:routes', async (ctx) => {
// Fetch all blog posts
const posts = await queryCollection('blog')
.where('draft', '<>', true)
.all()
// Generate routes for each post
for (const post of posts) {
ctx.routes.add(post.path)
}
})
})
```
**Benefits:**
- تشخیص خودکار تمام پست‌های بلاگ
- عدم نیاز به لیست دستی مسیرها
- پشتیبانی از draft posts (حذف از pre-render)
### 3. Sitemap Module Integration
**Purpose:** تولید خودکار sitemap.xml برای SEO
**Module:** `@nuxtjs/sitemap` یا `nuxt-simple-sitemap`
**Configuration:**
```typescript
// nuxt.config.ts
modules: [
'@nuxtjs/sitemap'
],
sitemap: {
hostname: 'https://aliarghyani.vercel.app',
gzip: true,
routes: async () => {
const posts = await queryCollection('blog')
.where('draft', '<>', true)
.all()
return posts.map(post => ({
url: post.path,
lastmod: post.updatedAt || post.date,
changefreq: 'monthly',
priority: 0.8
}))
}
}
```
**Output:**
- `/sitemap.xml` - sitemap اصلی
- شامل تمام پست‌های منتشر شده
- تاریخ آخرین تغییر برای هر URL
### 4. Build Script Optimization
**Purpose:** بهینه‌سازی فرآیند build برای SSG
**Location:** `package.json`
**Scripts:**
```json
{
"scripts": {
"build": "nuxt build",
"generate": "nuxt generate",
"preview": "nuxt preview"
}
}
```
**Command Usage:**
- `pnpm generate` - تولید فایل‌های استاتیک کامل
- خروجی در `.output/public`
## Data Models
### Blog Post Route Structure
```typescript
interface BlogRoute {
path: string // e.g., "/blog/post-slug" or "/fa/blog/post-slug"
locale: 'en' | 'fa'
slug: string
lastmod: string // ISO 8601 date
priority: number // 0.0 to 1.0
}
```
### Prerender Context
```typescript
interface PrerenderContext {
routes: Set<string> // مجموعه مسیرهای برای pre-render
}
```
## Error Handling
### 1. Missing Content Files
**Scenario:** فایل markdown وجود ندارد
**Handling:**
- در زمان build، خطا نمایش داده شود
- Build process متوقف شود
- پیام خطای واضح برای developer
### 2. Invalid Frontmatter
**Scenario:** frontmatter پست بلاگ نامعتبر است
**Handling:**
- Validation در زمان build
- خطای واضح با نام فایل
- پیشنهاد فرمت صحیح
### 3. Broken Internal Links
**Scenario:** لینک داخلی به صفحه‌ای اشاره می‌کند که وجود ندارد
**Handling:**
- Warning در build logs
- ادامه build process
- لیست لینک‌های شکسته در انتهای build
### 4. Build Timeout
**Scenario:** pre-rendering زمان زیادی می‌برد
**Handling:**
- تنظیم timeout مناسب در Nitro config
- نمایش progress در console
- امکان افزایش timeout برای بلاگ‌های بزرگ
## Testing Strategy
### 1. Build Testing
**Objective:** اطمینان از موفقیت build process
**Tests:**
- اجرای `pnpm generate` و بررسی exit code
- بررسی وجود فایل‌های HTML در `.output/public`
- بررسی تعداد فایل‌های تولید شده
**Example:**
```bash
pnpm generate
# Check exit code
echo $? # Should be 0
# Check generated files
ls -la .output/public/blog/
ls -la .output/public/fa/blog/
```
### 2. Route Coverage Testing
**Objective:** اطمینان از pre-render تمام مسیرها
**Tests:**
- بررسی وجود HTML برای هر پست بلاگ
- بررسی صفحات index
- بررسی هر دو locale
**Example:**
```bash
# Check English blog posts
test -f .output/public/blog/index.html
test -f .output/public/blog/post-slug/index.html
# Check Persian blog posts
test -f .output/public/fa/blog/index.html
test -f .output/public/fa/blog/post-slug/index.html
```
### 3. Sitemap Validation
**Objective:** اطمینان از صحت sitemap
**Tests:**
- بررسی وجود `/sitemap.xml`
- Validation XML syntax
- بررسی تعداد URLها
- بررسی فرمت تاریخ‌ها
**Example:**
```bash
# Check sitemap exists
test -f .output/public/sitemap.xml
# Validate XML
xmllint --noout .output/public/sitemap.xml
```
### 4. Content Integrity Testing
**Objective:** اطمینان از صحت محتوای pre-rendered
**Tests:**
- بررسی وجود meta tags در HTML
- بررسی وجود محتوای کامل
- بررسی structured data (JSON-LD)
**Example:**
```bash
# Check meta tags
grep -q "og:title" .output/public/blog/post-slug/index.html
grep -q "application/ld+json" .output/public/blog/post-slug/index.html
```
### 5. Performance Testing
**Objective:** اندازه‌گیری بهبود performance
**Metrics:**
- زمان بارگذاری صفحه
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- Time to Interactive (TTI)
**Tools:**
- Lighthouse CI
- WebPageTest
- Chrome DevTools
## Implementation Phases
### Phase 1: Basic SSG Setup
- پیکربندی Nitro prerender
- تست با چند پست نمونه
### Phase 2: Dynamic Route Generation
- پیاده‌سازی prerender hook
- تشخیص خودکار تمام پست‌ها
### Phase 3: Sitemap Integration
- نصب و پیکربندی sitemap module
- تولید sitemap با تمام مسیرها
### Phase 4: Optimization & Testing
- بهینه‌سازی build process
- تست کامل و validation
## Deployment Considerations
### Static Hosting Options
**Recommended Platforms:**
1. **Vercel** - بهترین گزینه برای Nuxt
2. **Netlify** - پشتیبانی عالی از SSG
3. **Cloudflare Pages** - سریع و رایگان
4. **GitHub Pages** - رایگان برای پروژه‌های عمومی
### Build Command
```bash
pnpm generate
```
### Output Directory
```
.output/public
```
### Environment Variables
```env
NUXT_PUBLIC_SITE_URL=https://aliarghyani.vercel.app
```
## Performance Expectations
### Before SSG (SSR)
- TTFB: 200-500ms
- FCP: 800-1200ms
- LCP: 1500-2500ms
### After SSG
- TTFB: 50-100ms (از CDN)
- FCP: 300-600ms
- LCP: 600-1200ms
**Expected Improvement:** 50-70% بهبود در زمان بارگذاری
## Maintenance
### Adding New Posts
1. اضافه کردن فایل markdown به `content/`
2. اجرای `pnpm generate`
3. Deploy فایل‌های جدید
### Updating Existing Posts
1. ویرایش فایل markdown
2. اجرای `pnpm generate`
3. Deploy مجدد
### No Server Maintenance Required
- نیازی به نگهداری سرور Node.js نیست
- فقط فایل‌های استاتیک
- کاهش هزینه‌های infrastructure
@@ -0,0 +1,83 @@
# Requirements Document
## Introduction
این سند نیازمندی‌های پیاده‌سازی کامل Static Site Generation (SSG) برای بلاگ را مشخص می‌کند. هدف اصلی بهبود performance، SEO و کاهش هزینه‌های هاستینگ از طریق pre-rendering تمام صفحات بلاگ در زمان build است.
## Glossary
- **Blog_System**: سیستم مدیریت و نمایش محتوای بلاگ در اپلیکیشن Nuxt
- **SSG (Static Site Generation)**: فرآیند تولید فایل‌های HTML استاتیک در زمان build
- **Pre-rendering**: تولید HTML از قبل برای صفحات در زمان build
- **Nuxt_Content**: ماژول Nuxt برای مدیریت محتوای markdown
- **Sitemap**: فایل XML حاوی لیست تمام URLهای سایت برای موتورهای جستجو
- **Build_Process**: فرآیند تبدیل کد منبع به فایل‌های قابل استقرار
## Requirements
### Requirement 1
**User Story:** به عنوان یک کاربر، می‌خواهم صفحات بلاگ با سرعت بالا بارگذاری شوند تا تجربه کاربری بهتری داشته باشم
#### Acceptance Criteria
1. WHEN a user navigates to any blog post, THE Blog_System SHALL serve a pre-rendered HTML file
2. WHEN a user navigates to the blog index page, THE Blog_System SHALL serve a pre-rendered HTML file
3. THE Blog_System SHALL generate all blog routes during the Build_Process
4. THE Blog_System SHALL include both English and Persian blog routes in pre-rendering
### Requirement 2
**User Story:** به عنوان یک توسعه‌دهنده، می‌خواهم تمام مسیرهای بلاگ به صورت خودکار شناسایی و pre-render شوند تا نیازی به مدیریت دستی نباشد
#### Acceptance Criteria
1. THE Blog_System SHALL automatically discover all markdown files in the content directory during Build_Process
2. THE Blog_System SHALL generate routes for all discovered blog posts in both locales
3. WHEN new blog posts are added to the content directory, THE Blog_System SHALL include them in the next Build_Process
4. THE Blog_System SHALL exclude draft posts from pre-rendering
### Requirement 3
**User Story:** به عنوان یک مدیر سایت، می‌خواهم sitemap خودکار تولید شود تا SEO بهتری داشته باشم
#### Acceptance Criteria
1. THE Blog_System SHALL generate an XML sitemap during Build_Process
2. THE Blog_System SHALL include all published blog posts in the sitemap
3. THE Blog_System SHALL include both English and Persian URLs in the sitemap
4. THE Blog_System SHALL include lastmod dates for each URL in the sitemap
5. THE Blog_System SHALL exclude draft posts from the sitemap
### Requirement 4
**User Story:** به عنوان یک توسعه‌دهنده، می‌خواهم فرآیند build بهینه باشد تا زمان deployment کاهش یابد
#### Acceptance Criteria
1. THE Blog_System SHALL use efficient crawling strategies to discover routes
2. THE Blog_System SHALL cache unchanged pages during Build_Process where possible
3. THE Blog_System SHALL provide clear build logs showing pre-rendered routes
4. WHEN the Build_Process completes, THE Blog_System SHALL output all generated static files to the dist directory
### Requirement 5
**User Story:** به عنوان یک کاربر، می‌خواهم محتوای بلاگ برای موتورهای جستجو قابل دسترسی باشد تا بتوانم مطالب را از طریق جستجو پیدا کنم
#### Acceptance Criteria
1. THE Blog_System SHALL include complete HTML content in pre-rendered pages
2. THE Blog_System SHALL include proper meta tags in pre-rendered pages
3. THE Blog_System SHALL include structured data (JSON-LD) in pre-rendered pages
4. THE Blog_System SHALL ensure all internal links are functional in static output
### Requirement 6
**User Story:** به عنوان یک توسعه‌دهنده، می‌خواهم بتوانم سایت را روی هر CDN یا static hosting استقرار دهم
#### Acceptance Criteria
1. THE Blog_System SHALL generate a fully static output compatible with static hosting services
2. THE Blog_System SHALL not require a Node.js server for serving blog pages
3. THE Blog_System SHALL include all necessary assets in the static output
4. THE Blog_System SHALL generate proper fallback pages for 404 errors
@@ -0,0 +1,78 @@
# Implementation Plan
- [x] 1. Install and configure sitemap module
- Install `nuxt-simple-sitemap` package
- Add module to `nuxt.config.ts`
- Configure basic sitemap settings with site URL
- _Requirements: 3.1, 3.2, 3.3_
- [x] 2. Create dynamic route generator for blog posts
- Create `server/plugins/prerender.ts` file
- Implement Nitro hook to discover all blog posts
- Add all non-draft blog post routes to prerender context
- Handle both English and Persian locales
- _Requirements: 2.1, 2.2, 2.3, 2.4_
- [ ] 3. Configure Nitro prerender settings
- Update `nitro.prerender` configuration in `nuxt.config.ts`
- Enable `crawlLinks` for automatic link discovery
- Add seed routes for blog index pages (`/blog`, `/fa/blog`)
- Configure prerender to exclude draft posts
- _Requirements: 1.3, 1.4, 4.1_
- [ ] 4. Implement sitemap dynamic routes
- Configure sitemap module to fetch blog posts dynamically
- Map blog posts to sitemap entries with proper metadata
- Include `lastmod`, `changefreq`, and `priority` for each entry
- Ensure draft posts are excluded from sitemap
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5_
- [ ] 5. Update build configuration
- Verify `nuxt generate` command in `package.json`
- Add environment variable for site URL if needed
- Document build process in README or comments
- _Requirements: 4.4, 6.1, 6.3_
- [x] 6. Test SSG build process
- Run `pnpm generate` command
- Verify all blog post HTML files are generated in `.output/public`
- Check both English and Persian blog routes
- Verify sitemap.xml is generated
- _Requirements: 1.1, 1.2, 4.3, 4.4_
- [ ]* 7. Validate generated output
- Check meta tags in generated HTML files
- Verify structured data (JSON-LD) is present
- Test internal links functionality
- Validate sitemap XML syntax
- _Requirements: 5.1, 5.2, 5.3, 5.4_
- [ ]* 8. Performance testing
- Measure page load times before and after SSG
- Run Lighthouse audit on generated pages
- Document performance improvements
- _Requirements: 1.1, 1.2_
- [x] 9. Update deployment documentation
- Document the `pnpm generate` command for deployment
- Specify output directory (`.output/public`)
- List compatible static hosting platforms
- Add environment variables needed for production
- _Requirements: 6.1, 6.2, 6.4_