Troubleshooting
Solutions to common issues when working with astro-gravatar components.
Common Issues
Section titled “Common Issues”Avatar Not Displaying
Section titled “Avatar Not Displaying”Problem
Section titled “Problem”Avatar images are not showing up or showing default placeholders.
Solutions
Section titled “Solutions”-
Check Email Hash Generation
import { hashEmail } from 'astro-gravatar';const hash = hashEmail('user@example.com');console.log('Hash:', hash); // Should be 64-character SHA256 hash -
Verify Default Image Settings
<GravatarAvataremail="user@example.com"default="identicon" <!-- Always show something -->/> -
Check Network Requests
- Open browser dev tools
- Look for failed image requests
- Verify the URL construction
Profile Data Missing
Section titled “Profile Data Missing”Problem
Section titled “Problem”Profile cards show empty or incomplete information.
Solutions
Section titled “Solutions”-
Use API Key for Complete Data
---import { getProfile } from 'astro-gravatar';const profile = await getProfile('user@example.com', {apiKey: import.meta.env.GRAVATAR_API_KEY});--- -
Handle Missing Profiles Gracefully
try {const profile = await getProfile('user@example.com');if (!profile) {// Use fallback datareturn createFallbackProfile();}} catch (error) {console.error('Profile fetch failed:', error);}
Performance Issues
Section titled “Performance Issues”Problem
Section titled “Problem”Slow loading or excessive API calls.
Solutions
Section titled “Solutions”-
Implement Caching
// Built-in caching is automaticimport { getApiCacheStats } from 'astro-gravatar';console.log('Cache stats:', getApiCacheStats()); -
Use Lazy Loading
<GravatarAvataremail="user@example.com"lazy={true}size={80}/> -
Batch Profile Requests
import { getProfiles } from 'astro-gravatar';const profiles = await getProfiles(['user1@example.com','user2@example.com','user3@example.com',]);
Error Codes and Solutions
Section titled “Error Codes and Solutions”Rate Limit Exceeded
Section titled “Rate Limit Exceeded”Error: Too many API requests
Solutions:
- Implement client-side caching
- Use API key for higher limits (1000/hour vs limited)
- Apply for increased limits at gravatar.com/developers
- Use exponential backoff for retries
// Exponential backoff implementationasync function fetchWithBackoff(email: string, retries = 3): Promise<Profile | null> { try { return await getProfile(email); } catch (error) { if (retries > 0 && error.code === 'rate_limit_exceeded') { const delay = Math.pow(2, 4 - retries) * 1000; // 1s, 2s, 4s await new Promise((resolve) => setTimeout(resolve, delay)); return fetchWithBackoff(email, retries - 1); } throw error; }}Authentication Failed
Section titled “Authentication Failed”Error: API key authentication failed
Solutions:
- Verify API key is correct
- Check environment variable setup
- Ensure no extra spaces in API key
- Use HTTPS for all requests
// Environment variable checkif (!import.meta.env.GRAVATAR_API_KEY) { console.warn('GRAVATAR_API_KEY not set. Profile data will be limited.');}Profile Not Found
Section titled “Profile Not Found”Error: User profile doesn’t exist or is disabled
Solutions:
- Use the user’s primary email address
- Check if user has disabled their profile
- Implement fallback handling
- Use default avatar styles
<GravatarAvatar email="user@example.com" default="identicon" onError={(e) => { // Fallback to custom avatar e.target.src = '/images/default-avatar.png'; }}/>Development Issues
Section titled “Development Issues”MDX Parsing Errors
Section titled “MDX Parsing Errors”Problem: <style> tags causing parsing errors in MDX files
Solution: Use separate CSS files or inline styles
/* Instead of <style> in MDX, create styles/gravatar.css */.custom-avatar { border: 2px solid #3b82f6; border-radius: 50%;}---import '../styles/gravatar.css';import GravatarAvatar from 'astro-gravatar';---
<GravatarAvatar email="user@example.com" class="custom-avatar"/>Component Import Errors
Section titled “Component Import Errors”Problem: Import paths not working correctly
Solution: Use the correct import syntax
<!-- Correct imports -->---import GravatarAvatar from 'astro-gravatar';import GravatarProfileCard from 'astro-gravatar/GravatarProfileCard';import { getProfile, hashEmail } from 'astro-gravatar';---
<!-- Incorrect import -->import * as Gravatar from 'astro-gravatar'; // Avoid thisTypeScript Errors
Section titled “TypeScript Errors”Problem: Type errors with component props
Solution: Import types explicitly
import type { GravatarProfile, GravatarAvatarProps, GravatarProfileCardProps,} from 'astro-gravatar';
const avatarProps: GravatarAvatarProps = { email: 'user@example.com', size: 80, default: 'identicon',};Browser Compatibility
Section titled “Browser Compatibility”IE11 Support
Section titled “IE11 Support”Problem: Components not working in Internet Explorer
Solution: Add appropriate polyfills
---// In your layout or main Astro file---
<script> // Polyfill for older browsers if (!window.fetch) { // Add fetch polyfill }
if (!window.IntersectionObserver) { // Add Intersection Observer polyfill for lazy loading }</script>Image Loading Issues
Section titled “Image Loading Issues”Problem: Avatars not loading in certain browsers
Solution: Add error handling and fallbacks
<GravatarAvatar email="user@example.com" size={80} onError={(e) => { // Fallback to identicon const fallbackUrl = `https://www.gravatar.com/avatar/${hashEmail(e.target.dataset.email)}?d=identicon&s=80`; e.target.src = fallbackUrl; }} data-email="user@example.com"/>Performance Optimization
Section titled “Performance Optimization”Large Avatar Lists
Section titled “Large Avatar Lists”Problem: Performance issues with many avatars on one page
Solution: Use lazy loading and pagination
---import GravatarAvatar from 'astro-gravatar';
const users = Array.from({length: 100}, (_, i) => ({ email: `user${i + 1}@example.com`, name: `User ${i + 1}`}));---
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(60px, 1fr)); gap: 1rem;"> {users.map((user) => ( <GravatarAvatar key={user.email} email={user.email} size={60} lazy={true} default="identicon" class="rounded-full" style="aspect-ratio: 1;" /> ))}</div>Caching Strategies
Section titled “Caching Strategies”Problem: Repeated API calls for same users
Solution: Implement server-side caching
// In an API route or server functionconst profileCache = new Map();
export async function getServerProfile(email: string) { if (profileCache.has(email)) { return profileCache.get(email); }
const profile = await getProfile(email, { apiKey: process.env.GRAVATAR_API_KEY, });
// Cache for 5 minutes profileCache.set(email, profile); setTimeout(() => profileCache.delete(email), 5 * 60 * 1000);
return profile;}Debugging Tools
Section titled “Debugging Tools”Profile URL Checker
Section titled “Profile URL Checker”import { buildAvatarUrl, hashEmail } from 'astro-gravatar';
function debugGravatar(email: string) { const hash = hashEmail(email); const avatarUrl = buildAvatarUrl(email, { size: 200 });
console.log('Email:', email); console.log('Hash:', hash); console.log('Avatar URL:', avatarUrl); console.log('Profile URL:', `https://gravatar.com/${hash}`); console.log('JSON Profile:', `https://gravatar.com/${hash}.json`);}
debugGravatar('user@example.com');Network Request Monitor
Section titled “Network Request Monitor”// Monitor Gravatar API requestsconst originalFetch = global.fetch;global.fetch = async function (url, options) { if (url.includes('gravatar.com')) { console.log('Gravatar Request:', url); console.log('Headers:', options?.headers); }
const response = await originalFetch(url, options);
if (url.includes('api.gravatar.com')) { console.log('Rate Limit Headers:', { limit: response.headers.get('X-RateLimit-Limit'), remaining: response.headers.get('X-RateLimit-Remaining'), reset: response.headers.get('X-RateLimit-Reset'), }); }
return response;};Getting Help
Section titled “Getting Help”Community Resources
Section titled “Community Resources”- GitHub Issues: Report bugs and request features
- Discussions: Ask questions and share examples
- Gravatar Documentation: Official API docs
Debug Information
Section titled “Debug Information”When reporting issues, include:
- Environment Info: Node version, Astro version, browser
- Code Example: Minimal reproduction of the issue
- Error Messages: Full error stack traces
- Network Logs: Failed request details
- Email Used: For testing purposes (can be dummy email)
Minimal Reproduction Template
Section titled “Minimal Reproduction Template”---import GravatarAvatar from 'astro-gravatar';---
<!-- Issue reproduction template --><GravatarAvatar email="test@example.com" size={80} default="identicon" class="rounded-full"/>Next Steps
Section titled “Next Steps”- Component Reference - Complete API documentation
- Authentication Guide - API key setup and usage
- API Endpoints - Direct API access
- Performance Guide - Optimization techniques