Tyler Dawson

I make apps, games, and whatevers.

Registering Vue Plugins in Nuxt 3 Projects

Note to self: here's how I can register a Vue plugin in my next Nuxt 3 project:

plugins/vue-safe-html.client.ts

import VueSafeHTML from "vue-safe-html";

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueSafeHTML, {
    allowedTags: ["strong"],
    allowedAttributes: ["class", "style"],
  });
});

The background...

I recently installed the vue-safe-html npm package in my Nuxt 3 project. It's a Vue directive that enables you to specify which tags and attributes you allow to render as HTML. All others get stripped.

After installation, I was a bit at a loss at how to actually use it within Nuxt. I knew I needed to call Vue.use() but wasn't sure where or how to access that. One of the things I love about Nuxt is how much of it is driven by standardized approaches that ultimately allow for consistency and things that automagically work. On the other hand, when I have a blind spot it can be hard to eve know where to begin.

The Nuxt packages directory is one of those magical places that will automatically register its files. I specified the .client suffix since mine wasn't needed on the server side, but that could be omitted or replaced with .server depending on your needs.

Importantly for this issue, the defineNuxtPlugin exposes nuxtApp, which has access to the vueApp. This is ultimately what was needed to register a Vue 3 plugin on my Nuxt 3 project. Magic.