How to Generate Gravatar Images with JavaScript/Node

Someone asked a question at the meetup today on how to create avatars on a site. The fastest method is probably to use Gravatar. Gravatar is a service that displays user profile pictures based on their email addresses. If the user hasn't signed up with Gravatar, a variety of default avatars can be shown.

Here is my Gravatar as an example:

Josh

In the simplest form, you load an image that is built with this structure:

https//www.gravatar.com/avatar/<md5sum_of_email_address>

Here's a solution that will work in Node.js, and allow you to choose a different type of default image for when an email address doesn't have a Gravatar:

const crypto = require('crypto');

function generateAvatarUrl(emailAddress, options = {}) {
    const defaultImage = options.defaultImage || 'identicon';
    const emailHash = crypto.createHash('md5').update(emailAddress).digest('hex');
    return `https://www.gravatar.com/avatar/${emailHash}?d=${defaultImage}`;
}

Then you can call the function with an email address to generate an image URL:

const avatarUrl = generateAvatarUrl('[email protected]');

When an email address doesn't have a gravatar, the function above will use an "identicon" by default, which looks like this:

Identicon

Or you could run the function like this:

const avatarUrl = generateAvatarUrl('[email protected]', { defaultImage: 'monsterid' });

to produce a random monster ID image by default:

Monster ID

There are more options available in the documentation.