Troubleshooting Guide
This guide helps you diagnose and fix common issues with the optimizer package. Use this page to quickly resolve problems with analytics, consent banners, SEO, and more.
Analytics Issues
Section titled “Analytics Issues”Analytics Not Tracking
Section titled “Analytics Not Tracking”Symptoms:
- No data in Google Analytics
- Events not appearing in GA4 DebugView
- Console shows no errors
Diagnosis:
// Open browser console and check:
// 1. Is gtag defined?console.log(typeof gtag); // Should be 'function'
// 2. Is dataLayer present?console.log(window.dataLayer); // Should be an array
// 3. Check GA4 IDconsole.log(window.dataLayer.find(item => item[0] === 'config')); // Should show your G-XXXXXXXXXX
// 4. Check if tracking is disabledconsole.log(window['ga-disable-G-XXXXXXXXXX']); // Should be undefined or falseSolutions:
-
Verify GA4 ID format
// ❌ Wrong: Old Universal Analytics formatgoogleAnalyticsId: 'UA-XXXXXXXXX-1'// ✅ Correct: GA4 formatgoogleAnalyticsId: 'G-XXXXXXXXXX' -
Check if running on localhost
// Analytics disabled on localhost by defaultconsole.log(window.location.hostname);// If 'localhost' or '127.0.0.1', analytics won't track// Solution: Test on actual domain or disable dev checkstarlightOptimizer({googleAnalyticsId: 'G-XXXXXXXXXX',disableInDev: false, // Allow tracking on localhost}) -
Verify consent was granted (EU users)
// Check consent stateconst consent = localStorage.getItem('cookie-consent');console.log(JSON.parse(consent));// Should show: { analytics: true, ... }// If analytics: false, user declined cookies// Ask user to accept via consent banner -
Check Do Not Track
// Check DNT statusconsole.log(navigator.doNotTrack);// If '1', analytics is disabled// Solution: Disable DNT check (not recommended)starlightOptimizer({respectDnt: false,}) -
Verify script injection
Terminal window # Check if GA4 script is in HTMLview-source:https://your-site.com# Search for:# - googletagmanager.com/gtag/js# - gtag('config', 'G-XXXXXXXXXX')# If missing, optimizer may not be configured correctly
Events Not Showing in GA4
Section titled “Events Not Showing in GA4”Symptoms:
- Page views work
- Custom events don’t appear in DebugView
- No errors in console
Solutions:
-
Check event syntax
// ❌ Wrong: Incorrect parameter namesgtag('event', 'button_click', {category: 'engagement', // Wrong parameter name});// ✅ Correct: Use event_categorygtag('event', 'button_click', {event_category: 'engagement',event_label: 'Download',value: 1,}); -
Verify event is firing
// Add debug loggingconst originalGtag = window.gtag;window.gtag = function(...args) {console.log('[GA4 Event]', ...args);return originalGtag.apply(this, args);};// Now trigger your event// Should see console log before sending to GA4 -
Check DebugView is enabled
// Enable debug modestarlightOptimizer({debug: true,})// Then check GA4 → Admin → DebugView
GA4 Script Blocked
Section titled “GA4 Script Blocked”Symptoms:
- Console error: “Failed to load resource”
- Blocked by adblocker
- CSP violation
Solutions:
-
Adblocker detection
// Detect if GA4 is blockedwindow.addEventListener('error', (e) => {if (e.target.src?.includes('googletagmanager.com')) {console.warn('Analytics blocked by adblocker');// Fallback: Track with first-party solutionuseFallbackTracking();}}, true); -
Content Security Policy fix
<!-- Add to HTML head or meta tag --><meta http-equiv="Content-Security-Policy" content="default-src 'self';script-src 'self' 'unsafe-inline' https://www.googletagmanager.com;connect-src 'self' https://www.google-analytics.com https://analytics.google.com;img-src 'self' data: https://www.google-analytics.com;">
GDPR/Consent Issues
Section titled “GDPR/Consent Issues”Consent Banner Not Showing
Section titled “Consent Banner Not Showing”Symptoms:
- Banner doesn’t appear for any users
- EU users don’t see consent prompt
Diagnosis:
// Check EU detectionconsole.log(window.__isEUUser); // Should be true for EU users
// Check if consent already givenconst consent = localStorage.getItem('cookie-consent');console.log(consent); // Should be null on first visit
// Check banner elementconst banner = document.querySelector('.cookie-consent-banner');console.log(banner); // Should exist if banner should showSolutions:
-
Verify GDPR is enabled
starlightOptimizer({gdprCompliance: true, // Make sure this is true (default)}) -
Clear localStorage
// Clear consent to test bannerlocalStorage.removeItem('cookie-consent');localStorage.removeItem('user-region-cache');location.reload(); -
Check timezone detection
// Test EU timezoneconsole.log(Intl.DateTimeFormat().resolvedOptions().timeZone);// Should be Europe/* for EU users// Force EU treatment for testingstarlightOptimizer({forceEUCompliance: true,}) -
Check CSS display
// Banner might be hidden by CSSconst banner = document.querySelector('.cookie-consent-banner');console.log(getComputedStyle(banner).display); // Should not be 'none'console.log(getComputedStyle(banner).visibility); // Should not be 'hidden'
Cookies Set Before Consent
Section titled “Cookies Set Before Consent”Symptoms:
- Analytics cookies present immediately
- No consent required
- GDPR violation
Diagnosis:
// On fresh page load, check cookies immediatelydocument.cookie.split(';').forEach(cookie => { console.log(cookie.trim());});
// For EU users, should ONLY see essential cookies// - cookie-consent (if set)// - session cookies// Should NOT see _ga, _gid before consentSolutions:
-
Verify Consent Mode defaults
// Check that consent mode defaults are set BEFORE GA4// View page source, should see:<script>// Consent defaults (first)gtag('consent', 'default', {...});</script><script async src="https://www.googletagmanager.com/gtag/js"></script><script>// GA4 init (after)gtag('config', 'G-XXX');</script> -
Check consent state
// Verify consent state in GA4gtag('get', 'G-XXXXXXXXXX', 'consent', (consent) => {console.log(consent);// For EU users without consent, should show:// { analytics_storage: 'denied', ... }}); -
Clear all cookies and test
// Delete all cookiesdocument.cookie.split(';').forEach(cookie => {const name = cookie.split('=')[0].trim();document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;});// Clear storagelocalStorage.clear();sessionStorage.clear();// Reload and verify no analytics cookies before consentlocation.reload();
Consent Not Persisting
Section titled “Consent Not Persisting”Symptoms:
- Banner appears on every page load
- Consent choice not saved
- LocalStorage not working
Solutions:
-
Check localStorage availability
// Test localStoragetry {localStorage.setItem('test', 'test');localStorage.removeItem('test');console.log('LocalStorage available');} catch (e) {console.error('LocalStorage not available:', e);// User might be in private/incognito mode// Or localStorage disabled in browser settings} -
Check for localStorage errors
// Listen for storage errorswindow.addEventListener('error', (e) => {if (e.message.includes('localStorage')) {console.error('LocalStorage error:', e);}}); -
Verify consent data format
// Check consent data structureconst consent = localStorage.getItem('cookie-consent');console.log(JSON.parse(consent));// Should be:// {// analytics: true/false,// timestamp: 1708185600000,// version: '1.0'// }
SEO Issues
Section titled “SEO Issues”OG Image Not Showing
Section titled “OG Image Not Showing”Symptoms:
- Facebook debugger shows no image
- Twitter card preview missing
- Social shares lack image
Solutions:
-
Verify image exists
Terminal window # Test image URL directlycurl -I https://docs.example.com/og-image.png# Should return: HTTP/1.1 200 OK -
Check absolute URL
<!-- ❌ Wrong: Relative URL --><meta property="og:image" content="/og-image.png"><!-- ✅ Correct: Absolute URL --><meta property="og:image" content="https://docs.example.com/og-image.png"> -
Verify image size
Terminal window # OG image should be:# - At least 1200x630 pixels# - Less than 1 MB# - PNG or JPEG format# Check file sizecurl -sI https://docs.example.com/og-image.png | grep -i content-length -
Clear social media cache
Terminal window # Facebook Sharing Debuggerhttps://developers.facebook.com/tools/debug/# Click "Scrape Again" to refresh cache# Twitter Card Validatorhttps://cards-dev.twitter.com/validator -
Check meta tag
Terminal window # Verify OG tag in HTMLcurl https://docs.example.com/page | grep og:image# Should output:# <meta property="og:image" content="https://docs.example.com/og-image.png">
Structured Data Errors
Section titled “Structured Data Errors”Symptoms:
- Google Rich Results Test shows errors
- Missing required fields
- Invalid schema
Solutions:
-
Test with Rich Results Test
https://search.google.com/test/rich-resultsCommon errors:- Missing 'author' field- Missing 'datePublished'- Invalid date format- Missing image -
Fix common errors
// ❌ Wrong: Invalid date"datePublished": "2025-02-17" // Missing time// ✅ Correct: ISO 8601 format"datePublished": "2025-02-17T10:00:00Z"// ❌ Wrong: Relative URL"image": "/logo.png"// ✅ Correct: Absolute URL"image": "https://docs.example.com/logo.png" -
Validate JSON-LD syntax
// Check for syntax errorsconst script = document.querySelector('script[type="application/ld+json"]');try {JSON.parse(script.textContent);console.log('Valid JSON-LD');} catch (e) {console.error('Invalid JSON-LD:', e);}
Search Engines Not Indexing
Section titled “Search Engines Not Indexing”Symptoms:
- Pages not appearing in Google
- Site:example.com shows no results
- Google Search Console shows coverage issues
Solutions:
-
Check robots.txt
# Visit: https://docs.example.com/robots.txt# Should NOT have:User-agent: *Disallow: / # This blocks all crawling# Should have:User-agent: *Allow: /Sitemap: https://docs.example.com/sitemap.xml -
Check meta robots tag
<!-- ❌ Wrong: Prevents indexing --><meta name="robots" content="noindex, nofollow"><!-- ✅ Correct: Allows indexing --><meta name="robots" content="index, follow"> -
Submit sitemap
1. Add @astrojs/sitemap integration2. Go to Google Search Console3. Sitemaps → Add sitemap4. Enter: https://docs.example.com/sitemap-index.xml5. Wait 24-48 hours for indexing -
Request indexing
Google Search Console:1. URL Inspection tool2. Enter page URL3. Click "Request Indexing"4. Wait 24-72 hours
LLM Optimization Issues
Section titled “LLM Optimization Issues”llms.txt Not Generated
Section titled “llms.txt Not Generated”Symptoms:
- /llms.txt returns 404
- File missing from build output
Solutions:
-
Verify LLM optimization enabled
starlightOptimizer({llmOptimization: true, // Make sure this is true}) -
Check build output
Terminal window # After buildls dist/llms.txt# Should exist# If missing, check build logs for errors -
Manually create llms.txt
Terminal window # Create in public/ directorytouch public/llms.txt# Add basic contentecho "# llms.txt" > public/llms.txtecho "## Documentation" >> public/llms.txt
AI Not Finding Documentation
Section titled “AI Not Finding Documentation”Symptoms:
- ChatGPT/Claude doesn’t reference your docs
- AI provides generic answers instead of your docs
Solutions:
-
Verify llms.txt format
# llms.txt must be:# - Plain text# - Markdown-compatible# - At root: /llms.txt (not /docs/llms.txt) -
Check robots.txt for AI crawlers
# Allow AI crawlersUser-agent: GPTBotUser-agent: ChatGPT-UserUser-agent: Claude-WebUser-agent: Anthropic-AIAllow: / -
Improve llms.txt content
# Make it discoverable:# - Clear section headings# - Descriptive page titles# - Include keywords# - Add context for AI
Build Issues
Section titled “Build Issues”Build Failing
Section titled “Build Failing”Symptoms:
npm run buildfails- TypeScript errors
- Integration errors
Solutions:
-
Check Astro version
Terminal window # Requires Astro 3.5+npm list astro# Update if needednpm update astro @astrojs/starlight -
Check Node version
Terminal window # Requires Node.js 18+node --version# Update if needed (use nvm)nvm install 18nvm use 18 -
Clear cache and rebuild
Terminal window # Clear Astro cacherm -rf .astro node_modules/.astro# Reinstall dependenciesrm -rf node_modules package-lock.jsonnpm install# Rebuildnpm run build -
Check configuration syntax
// Common errors:// ❌ Wrong: Missing commastarlightOptimizer({googleAnalyticsId: 'G-XXX'gdprCompliance: true // Missing comma before this})// ✅ CorrectstarlightOptimizer({googleAnalyticsId: 'G-XXX',gdprCompliance: true,})
TypeScript Errors
Section titled “TypeScript Errors”Symptoms:
- Type errors in astro.config.mjs
- Missing type definitions
Solutions:
-
Install type definitions
Terminal window npm install --save-dev @types/node -
Use proper TypeScript config
// Use .ts instead of .js for config// astro.config.ts (not .mjs)import type { AstroUserConfig } from 'astro/config';const config: AstroUserConfig = {// Full type checking};export default config;
Performance Issues
Section titled “Performance Issues”Slow Page Loads
Section titled “Slow Page Loads”Symptoms:
- Lighthouse score decreased
- Longer load times
- Blocking scripts
Solutions:
-
Check script loading
<!-- Ensure async loading --><script async src="https://www.googletagmanager.com/gtag/js"></script><!-- Not: --><script src="..."></script> <!-- Blocks rendering --> -
Reduce consent banner size
/* Minimize CSS in consent banner */.cookie-consent-banner {/* Only essential styles *//* Remove unnecessary animations *//* Reduce shadow/effects */} -
Test performance impact
Terminal window # Before optimizerlighthouse https://your-site.com --only-categories=performance# After optimizerlighthouse https://your-site.com --only-categories=performance# Compare scores
Getting Help
Section titled “Getting Help”If you can’t resolve your issue:
-
Check GitHub Issues
- Search existing issues: github.com/yourorg/optimizer/issues
- Common problems often already solved
-
Create New Issue
- Use issue template
- Include reproduction steps
- Provide config and error messages
- Specify versions (Astro, Starlight, Node)
-
Community Support
- GitHub Discussions
- Discord server (if available)
- Stack Overflow (tag: astro)
-
Debug Template
**Issue**: [Brief description]**Expected**: [What should happen]**Actual**: [What actually happens]**Environment**:- Astro version: X.X.X- Starlight version: X.X.X- Optimizer version: X.X.X- Node version: X.X.X- OS: [Windows/Mac/Linux]**Config**:\`\`\`javascript// Your astro.config.mjs\`\`\`**Steps to reproduce**:1. Step one2. Step two3. ...**Console errors** (if any):\`\`\`[Error messages]\`\`\`
Related Pages: