Stop using Gravatar libraries

Why Create Your Own Gravatar Library?

Gravatar is a convenient service for displaying user avatars, but relying on third-party libraries can sometimes introduce unnecessary dependencies and potential security risks. By creating your own Gravatar library, you have more control over the implementation and can tailor it to your specific needs.

In the code snippents please replace single quotes with a backtick. This was an issue with the markdown parser. Replase with backtiks for template literalst.

Building a Gravatar Component in React

Let's start with a React component that generates Gravatar URLs based on user email addresses.

const Gravatar = ({ email, className }) => {
  const [gravatarUrl, setGravatarUrl] = useState('')

  async function hashEmail(email) {
    const hashBuffer = await crypto.subtle.digest(
      'SHA-256',
      new TextEncoder().encode(email.toLowerCase().trim())
    )
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
  }

  useEffect(() => {
    async function getGravatarUrl() {
      const hash = await hashEmail(email)
      setGravatarUrl('https://www.gravatar.com/avatar/${hash}?default=mystery')
    }

    getGravatarUrl()
  }, [email])

  return <img src={gravatarUrl} alt="Avatar" className={className} />
}

Implementing a Vue Nuxt Component

For Vue/Nuxt users, here's a similar component using Vue 3 Composition API:

<script setup>
import { defineProps, ref, onMounted } from 'vue'

const props = defineProps({
  email: String,
})

const gravatarUrl = ref('')

async function hashEmail(email) {
  const hashBuffer = await crypto.subtle.digest(
    'SHA-256',
    new TextEncoder().encode(email.toLowerCase().trim())
  )
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
}

onMounted(async () => {
  const hash = await hashEmail(props.email)
  gravatarUrl.value = "https://gravatar.com/avatar/${hash}?default=mystery"
})
</script>

<template>
  <v-avatar color="grey-lighten-1">
    <v-img alt="Avatar" :src="gravatarUrl"></v-img>
  </v-avatar>
</template>

Conclusion

By creating your own Gravatar library, you gain more flexibility and control over how user avatars are displayed in your applications. This approach also reduces reliance on external dependencies, leading to a more streamlined and secure codebase.

Whether you're using React or Vue/Nuxt, implementing a custom Gravatar solution can be a rewarding and beneficial endeavor for your projects.