NuxtN
Nuxt14mo ago
6 replies
nikneym

Using protobufs with Nuxt

Hi, I'm trying to integrate google protocol buffers to nuxt to use together with websockets. I've searched through the web but couldn't find any resources so I've came up with my own to provide build artifacts to my app:
import { createResolver } from "nuxt/kit";
import pbjs from "protobufjs-cli/pbjs";

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: "2024-11-01",
  devtools: { enabled: true },
  nitro: {
    experimental: {
      websocket: true,
    },
  },
  hooks: {
    // creates protobufs at build time
    "app:templates": (app) => {
      const { resolve } = createResolver(import.meta.url);
      const dir = resolve("./proto");

      pbjs.main(["--target", "json", dir + "/test.proto"], (err, output) => {
        if (err !== null) {
          throw err;
        }

        app.templates.push({
          filename: "protobuf.json",
          // intentionally write to disk
          write: true,
          getContents: () => output!,
        });
      });
    },
    "app:templatesGenerated": () => {
      console.info("Templates are generated successfully");
    },
  },
});

Is this the preferred way? Thanks in advance.
Was this page helpful?