# Next.js Frontend Setup Guide Complete installation and configuration guide for the Next.js frontend component of the Planit AI template. ## 📋 Prerequisites - **Node.js** 18 or higher - **yarn** package manager (required) - WordPress backend already set up and accessible - reCAPTCHA Site Key (from WordPress setup) ## 🚀 Installation ### Step 1: Install Dependencies ```bash cd nextjs yarn install ``` ### Step 2: Configure Environment Variables 1. **Copy Environment Template** ```bash cp env.example .env.local ``` 2. **Edit `.env.local` File** Open `.env.local` and update the values: ```env NEXT_PUBLIC_WP_API_BASE=https://your-wordpress-domain.com/api/wp/v2 NEXT_PUBLIC_RECAPTCHA_SITE_KEY=your_recaptcha_site_key_here ``` 3. **Update Values** - Replace `your-wordpress-domain.com` with your actual WordPress domain - Use the **same Site Key** from WordPress reCAPTCHA setup - Ensure URLs use `https://` in production **Note:** The `env.example` file is provided as a template. Copy it to `.env.local` and update with your actual values. ### Step 3: Update API Configuration (If Needed) 1. **Check Contact Form ID** - Open `lib/api.ts` - Find `submitContactForm` function - Verify form ID matches WordPress (default: 219) - Update if different: ```typescript const url = `https://your-wordpress-domain.com/api/contact-form-7/v1/contact-forms/YOUR_FORM_ID/feedback`; ``` ### Step 4: Run Development Server ```bash yarn dev ``` Open [http://localhost:3000](http://localhost:3000) in your browser. ## 🛠️ Development ### Available Scripts - `yarn dev` - Start development server - `yarn build` - Build for production - `yarn start` - Start production server - `yarn lint` - Run linter ### Project Structure ``` nextjs/ ├── app/ # Next.js App Router pages │ ├── blogs/ # Blog pages │ ├── news/ # News pages │ ├── contact/ # Contact page │ └── layout.tsx # Root layout ├── components/ # React components │ ├── blogs/ # Blog components │ ├── news/ # News components │ └── ui/ # UI components ├── lib/ # Utilities │ └── api.ts # WordPress API integration └── public/ # Static assets ``` ### Key Files - `lib/api.ts` - WordPress REST API integration - `app/layout.tsx` - Root layout with providers - `next.config.ts` - Next.js configuration - `components/pages/contact/contact-form.tsx` - Contact form with reCAPTCHA ## 🔧 Configuration ### WordPress API Integration The frontend connects to WordPress via REST API: - **Base URL:** Set in `NEXT_PUBLIC_WP_API_BASE` - **Endpoints:** - `/posts` - Get blog posts and news - `/posts/{id}` - Get single post - `/posts?slug={slug}` - Get post by slug - `/contact-form-7/v1/contact-forms/{id}/feedback` - Submit contact form ### reCAPTCHA Configuration - Uses reCAPTCHA v3 (invisible) - Executes automatically on form submission - Requires Site Key in `NEXT_PUBLIC_RECAPTCHA_SITE_KEY` ### On-Demand Revalidation (ISR → OSG Migration) #### Background Previously, we used ISR (Incremental Static Regeneration) with a 60-second revalidation interval to refresh WordPress content. **How ISR works:** - Static pages are generated at build time - Cached pages are served for 60 seconds - After 60 seconds, if someone visits the page, it regenerates in the background - If no visitors, no regeneration occurs **However, this caused issues:** 1. **Continuous traffic triggers regeneration** - Crawlers (Google, Bing, etc.) and regular visitors trigger API calls after every 60-second interval 2. **Multiple pages regenerating simultaneously** - When multiple pages revalidate at once, requests spike 3. **Server blocking** - onamaeweb.jp server detected repeated requests as DDoS/bot activity and banned the IP 4. **Build failures** - Vercel builds failed with 403 Forbidden when accessing WordPress API 5. **Inefficient resource usage** - Unnecessary regeneration even when content hadn't changed #### New Approach: On-Demand Revalidation WordPress sends a webhook to Next.js only when content changes, invalidating the cache on demand. **Benefits:** - No unnecessary API calls - Eliminates server blocking risk - Immediate content updates when changes occur - Efficient resource usage #### Setup Instructions ##### 1. Add Vercel Environment Variable In Vercel Dashboard → Settings → Environment Variables, add: ```env REVALIDATE_SECRET=your-random-secret-token-here ``` **Important:** Use a sufficiently long random string. ##### 2. Configure WordPress Webhook **Install WP Webhooks Plugin:** 1. WordPress Admin → Plugins → Add New 2. Search for "WP Webhooks" and install - Plugin name: **WP Webhooks – Automate repetitive tasks by creating powerful automation workflows directly within WordPress** 3. Activate the plugin **Configure Webhooks:** 1. WordPress Admin → WP Webhooks → Send Data 2. Add webhooks for the following triggers: - `post_create` (post creation) - `post_update` (post update) - `post_delete` (post deletion) 3. Configure each webhook: - **Webhook URL:** `https://www.planitai.co.jp/api/revalidate` - **Request Method:** POST - **Headers:** ``` x-revalidate-secret: your-random-secret-token-here Content-Type: application/json ``` ##### 3. Testing After setup, test the endpoint: ```bash # GET method test curl "https://www.planitai.co.jp/api/revalidate?secret=your-random-secret-token-here" # POST method test curl -X POST https://www.planitai.co.jp/api/revalidate \ -H "x-revalidate-secret: your-random-secret-token-here" \ -H "Content-Type: application/json" \ -d '{"slug": "test-post"}' ``` Success response: ```json { "revalidated": true, "timestamp": 1234567890 } ``` ##### 4. Initial Revalidation (Required) After deployment, you must trigger an initial revalidation to populate the cache with WordPress content. **How revalidation works:** - Without `slug`: Revalidates `revalidateTag('posts')` and main paths (`/`, `/blogs`, `/news`) - With `slug`: Additionally revalidates specific post pages (`/blogs/specific-post`) For initial revalidation, you need to fetch all content, so call without `slug`: ```bash curl -X POST https://www.planitai.co.jp/api/revalidate \ -H "x-revalidate-secret: LWCTd22HKmCa8uNqOvaoTYlXoNONFVlhx" \ -H "Content-Type: application/json" \ -d '{}' ``` Or use GET method for simplicity: ```bash curl "https://www.planitai.co.jp/api/revalidate?secret=LWCTd22HKmCa8uNqOvaoTYlXoNONFVlhx" ``` This is necessary because the build process may not have access to WordPress API (due to IP blocking), so the initial content must be fetched via this revalidation call. ##### 5. Test from WordPress 1. Create a new post or edit an existing post in WordPress 2. Verify the changes are immediately reflected on the site ## ✅ Testing ### Verify Setup 1. **Check API Connection** ```bash curl https://your-wordpress-domain.com/api/wp/v2/posts?per_page=1 ``` Should return JSON with post data 2. **Test Locally** - Run `yarn dev` - Visit `http://localhost:3000` - Check blog/news pages load - Test contact form ### Test Checklist - [ ] Homepage loads - [ ] Blog posts display from WordPress - [ ] News posts display from WordPress - [ ] Individual post pages load with content - [ ] Contact form submits successfully - [ ] reCAPTCHA works (invisible) - [ ] Images load correctly ## 🚀 Deployment ### Option 1: Vercel (Recommended) 1. **Push to Git Repository** ```bash git init git add . git commit -m "Initial commit" git remote add origin git push -u origin main ``` 2. **Deploy to Vercel** - Connect repository to Vercel - Add environment variables: - `NEXT_PUBLIC_WP_API_BASE` - `NEXT_PUBLIC_RECAPTCHA_SITE_KEY` - Deploy ### Option 2: Custom Server 1. **Build Application** ```bash yarn build ``` 2. **Start Production Server** ```bash yarn start ``` 3. **Configure Server** - Use PM2 for process management - Configure Nginx reverse proxy - Set up SSL certificate ## 🔧 Troubleshooting **Build errors:** - Check TypeScript errors: `yarn lint` - Verify environment variables are set - Check for missing dependencies **API connection errors:** - Verify WordPress API URL is correct - Check CORS settings in WordPress - Ensure WordPress REST API is enabled **Contact form errors:** - Check browser console for errors - Verify reCAPTCHA keys - Check form ID matches WordPress **Images not loading:** - Check WordPress image URLs in API response - Verify Next.js image configuration - Check `next.config.ts` for image domains ## 📚 Next Steps After Next.js is running: 1. Test all pages and functionality 2. Configure production deployment 3. Set up monitoring and analytics 4. Review performance optimization ## 📚 Additional Resources - [Next.js Documentation](https://nextjs.org/docs) - [React Documentation](https://react.dev) - [TypeScript Documentation](https://www.typescriptlang.org/docs) - [Tailwind CSS Documentation](https://tailwindcss.com/docs) --- For complete setup including WordPress, see `../SETUP-GUIDE.md`