2.7 KiB
Ngrok CORS/Mixed Content Fix
Problem
When accessing the website through ngrok (HTTPS), you were getting:
Console TypeError: Failed to fetch
Root Cause
-
Mixed Content Issue: Ngrok serves your site over HTTPS, but your components were making direct HTTP requests to Strapi (
http://160.187.167.213). Browsers block HTTP requests from HTTPS pages for security reasons. -
CORS Issues: Even if the protocol matched, Strapi might not be configured to allow requests from the ngrok domain.
-
Client-Side Fetching: All components were making API calls directly from the browser, which exposes your Strapi URL and causes CORS/mixed content issues.
Solution
Created Next.js API routes that act as a proxy between your frontend and Strapi:
New API Routes Created:
/api/logo- Fetches logo data/api/main-hero- Fetches main hero content/api/testimonials- Fetches testimonials/api/trusted-by- Fetches trusted-by section data/api/offerings- Fetches offerings data/api/footer- Fetches all footer data (consolidated 7 API calls into 1)
Components Updated:
- ✅
navbar.tsx- Now uses/api/logo - ✅
main-hero.tsx- Now uses/api/main-hero - ✅
hero-section.tsx- Already uses/api/whysfs(no change needed) - ✅
testimonials.tsx- Now uses/api/testimonials - ✅
trusted-by.tsx- Now uses/api/trusted-by - ✅
footer.tsx- Now uses/api/footer(consolidated 7 calls into 1) - ✅
our-offerings.tsx- Server component, no CORS issue (kept direct Strapi call)
Benefits
- No More CORS Errors: All requests go through Next.js server, which doesn't have CORS restrictions
- No Mixed Content Issues: Server-to-server communication doesn't have protocol restrictions
- Better Performance:
- API routes are cached (5 minutes)
- Footer consolidated from 7 calls to 1
- Reduced network overhead
- Security: Strapi URL is no longer exposed to the browser
- Easier Debugging: All API calls go through Next.js, easier to log and debug
Testing
After these changes, your website should work correctly when accessed through ngrok. The API routes handle all the communication with Strapi server-side, avoiding browser security restrictions.
Next Steps (Optional Improvements)
- Add Error Handling: Add retry logic and better error messages
- Add Loading States: Show loading indicators while data is being fetched
- Optimize Caching: Adjust cache times based on how often content changes
- Add Request Logging: Log API calls for debugging in production
Environment Variables
Make sure your .env.local has:
NEXT_PUBLIC_STRAPI_BASE_URL=http://160.187.167.213
The API routes use this to connect to Strapi server-side.