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:


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


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
    return `${emailHash}?d=${defaultImage}`;

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

const avatarUrl = generateAvatarUrl("");

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


Or you could run the function like this:

const avatarUrl = generateAvatarUrl("", {
    defaultImage: "monsterid",

to produce a random monster ID image by default:

Monster ID

There are more options available in the documentation.