Skip to content

Utilities Reference

Reference for the non-component exports exposed by astro-gravatar.

Build a Gravatar avatar URL from an email address.

import { buildAvatarUrl } from 'astro-gravatar';
const url = await buildAvatarUrl('user@example.com', {
size: 200,
rating: 'pg',
default: 'identicon',
forceDefault: true,
});

Options

OptionTypeDefaultDescription
sizenumber80Avatar size in pixels (1-2048)
rating'g' | 'pg' | 'r' | 'x''g'Maximum rating level
defaultDefaultAvatar'mp'Default avatar type or custom URL
forceDefaultbooleanfalseForce the default image even when a real avatar exists

Returns

  • Promise<string>: Complete avatar URL

Build the Gravatar API profile endpoint URL for an email address.

import { buildProfileUrl } from 'astro-gravatar';
const url = await buildProfileUrl('user@example.com', {
baseUrl: 'https://api.gravatar.com/v3',
});

Options

OptionTypeDefaultDescription
baseUrlstringhttps://api.gravatar.com/v3Override the profile API base URL

Build a Gravatar QR code URL from an email address.

import { buildQRCodeUrl } from 'astro-gravatar';
const url = await buildQRCodeUrl('user@example.com', {
size: 160,
version: 3,
type: 'gravatar',
utmMedium: 'docs',
utmCampaign: 'launch',
});

Options

OptionTypeDefaultDescription
sizenumber80QR code size in pixels (1-1000)
version1 | 31QR style version
type'user' | 'gravatar' | 'none''none'Center icon
utmMediumstringundefinedutm_medium query value
utmCampaignstringundefinedutm_campaign query value

Fetch a single Gravatar profile.

import { getProfile } from 'astro-gravatar';
const profile = await getProfile('user@example.com', {
apiKey: import.meta.env.GRAVATAR_API_KEY,
});

Options

OptionTypeDefaultDescription
apiKeystringundefinedBearer token for richer profile access
baseUrlstringhttps://api.gravatar.com/v3Override API base URL
timeoutnumber10000Request timeout in milliseconds
headersRecord<string, string>undefinedExtra request headers

Returns

  • Promise<GravatarProfile>: Parsed profile payload

Fetch multiple profiles in parallel.

import { getProfiles } from 'astro-gravatar';
const profiles = await getProfiles(['alice@example.com', 'bob@example.com'], {
apiKey: import.meta.env.GRAVATAR_API_KEY,
});

Returns

  • Promise<GravatarProfile[]>: Array of successful profile results. Failed lookups are skipped unless every lookup fails, in which case the first GravatarError is re-thrown.

Validate avatar sizing and rating before rendering or URL generation.

import { validateAvatarParams } from 'astro-gravatar';
validateAvatarParams(128, 'pg');

Throws GravatarError when the size or rating is invalid.

Read the package’s default avatar settings.

import { getDefaultAvatarConfig } from 'astro-gravatar';
const defaults = getDefaultAvatarConfig();
// { size: 80, rating: 'g', default: 'mp', forceDefault: false }

Hash an email address with SHA256 for Gravatar usage.

import { hashEmail } from 'astro-gravatar';
const hash = await hashEmail('user@example.com');

Hash multiple email addresses in one call.

import { hashEmails } from 'astro-gravatar';
const hashes = await hashEmails(['alice@example.com', 'bob@example.com']);

Validate email syntax before attempting a request.

import { isValidEmail } from 'astro-gravatar';
if (isValidEmail('user@example.com')) {
console.log('Looks valid');
}

Trim and lowercase an email address using the same normalization rules the package uses internally.

import { normalizeEmail } from 'astro-gravatar';
const normalized = normalizeEmail(' User@Example.com ');
// "user@example.com"

Accept a Gravatar hash, a Gravatar profile URL, or an email address and resolve it to a SHA256 hash.

import { extractHash } from 'astro-gravatar';
const hashA = await extractHash('user@example.com');
const hashB = await extractHash(
'https://gravatar.com/27205e5c51cb03f862138b22bcb5dc20f94a342e744ff6df1b8dc8af3c865109',
);

Hash an email address with the built-in in-memory cache enabled by default.

import { hashEmailWithCache } from 'astro-gravatar';
const hash = await hashEmailWithCache('user@example.com');

Pass false as the second argument to bypass the cache.

Clear the email hash cache.

import { clearEmailHashCache } from 'astro-gravatar';
clearEmailHashCache();

Inspect email hash cache size and limits.

import { getEmailHashCacheStats } from 'astro-gravatar';
const stats = getEmailHashCacheStats();
// { size, maxSize, ttl }

Clear the simple in-memory API cache used by the top-level profile helpers.

import { clearApiCache } from 'astro-gravatar';
clearApiCache();

Read API cache statistics for the top-level helpers.

import { getApiCacheStats } from 'astro-gravatar';
const stats = getApiCacheStats();
console.log(stats.size);
console.log(stats.entries);

The top-level helper cache reports its current size and entry expiration metadata.

Use GravatarClient when you need advanced retry, cache, header, or rate-limit control beyond the top-level helpers.

import { GravatarClient } from 'astro-gravatar';
const client = new GravatarClient({
apiKey: import.meta.env.GRAVATAR_API_KEY,
timeout: 15000,
cache: {
enabled: true,
ttl: 300,
maxSize: 1000,
},
});
const profile = await client.getProfile('user@example.com');

Common methods:

  • client.getProfile(email, options?)
  • client.getProfiles(emails, options?)
  • client.clearCache()
  • client.getCacheStats()
  • client.getRequestStats()

GravatarError is thrown for invalid input, request failures, and API errors.

import { getProfile, GravatarError, GRAVATAR_ERROR_CODES } from 'astro-gravatar';
try {
await getProfile('user@example.com');
} catch (error) {
if (
error instanceof GravatarError &&
error.code === GRAVATAR_ERROR_CODES.RATE_LIMITED
) {
console.log('Retry later', error.rateLimit);
}
}

Available properties:

  • message
  • code
  • status
  • rateLimit

The exported error code map is useful when you want stable comparisons instead of raw strings.

import { GRAVATAR_ERROR_CODES } from 'astro-gravatar';
console.log(GRAVATAR_ERROR_CODES.RATE_LIMITED);

These constants are part of the public package surface:

ConstantValue
GRAVATAR_AVATAR_BASEhttps://0.gravatar.com/avatar
GRAVATAR_API_BASEhttps://api.gravatar.com/v3
GRAVATAR_QR_BASEhttps://api.gravatar.com/v3/qr-code
DEFAULT_AVATAR_SIZE80
DEFAULT_AVATAR_RATING'g'
DEFAULT_AVATAR_IMAGE'mp'
DEFAULT_TIMEOUT10000

Representative public types from astro-gravatar/types:

interface VerifiedAccount {
service_type: string;
service_label: string;
service_icon: string;
url: string;
is_hidden: boolean;
}
interface Link {
label: string;
url: string;
}
interface GravatarProfile {
hash: string;
profile_url: string;
avatar_url: string;
avatar_alt_text: string;
display_name: string;
verified_accounts?: VerifiedAccount[];
links?: Link[];
is_organization?: boolean;
background_color?: string;
number_verified_accounts?: number;
}

For the full exported type surface, import from:

import type { GravatarProfile, GravatarAvatarProps } from 'astro-gravatar';
import type { VerifiedAccount } from 'astro-gravatar/types';

The package also ships a CLI for offline URL generation. See the CLI guide for command usage and examples.