question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Does not work with Vite/Sveltekit

See original GitHub issue

Error only occurs when running npm run build:

> Using @sveltejs/adapter-netlify
> Named export 'Webhooks' not found. The requested module '@mux/mux-node' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@mux/mux-node';
const { Webhooks } = pkg;

file:///Users/ben/dev/mux-node-esm-issue/.svelte-kit/output/server/app.js:4
import { Webhooks } from "@mux/mux-node";
         ^^^^^^^^
SyntaxError: Named export 'Webhooks' not found. The requested module '@mux/mux-node' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@mux/mux-node';
const { Webhooks } = pkg;

    at ModuleJob._instantiate (internal/modules/esm/module_job.js:97:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:142:20)
    at async Loader.import (internal/modules/esm/loader.js:182:24)
    at async prerender (file:///Users/ben/dev/mux-node-esm-issue/node_modules/@sveltejs/kit/dist/chunks/index6.js:80:14)
    at async Object.prerender (file:///Users/ben/dev/mux-node-esm-issue/node_modules/@sveltejs/kit/dist/chunks/index6.js:312:5)
    at async adapt (file:///Users/ben/dev/mux-node-esm-issue/node_modules/@sveltejs/adapter-netlify/index.js:34:4)
    at async adapt (file:///Users/ben/dev/mux-node-esm-issue/node_modules/@sveltejs/kit/dist/chunks/index6.js:338:2)
    at async file:///Users/ben/dev/mux-node-esm-issue/node_modules/@sveltejs/kit/dist/cli.js:887:5

adapter-netlify / SvelteKit are not recognising @mux/mux-node as an ESM package. This could be due to "type": "module" not being present in the package.json. Could also be that "main": "src/index.js" needs to be replaced with "exports": "src/index.js"

EDIT: Repro repo: https://github.com/benwoodward/mux-node-esm-issue (Run npm run build to see the error`)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:9

github_iconTop GitHub Comments

2reactions
dylanjhacommented, Jul 7, 2021

@benwoodward ah yeah, you’re totally right 😄

Webhooks is a static attribute on the Mux constructor whereas Video and Data are on the instance. Thanks for clarifying and posting the code sample!

import Mux from '@mux/mux-node';

const { Webhooks } = Mux
const { Video, Data } = new Mux(accessToken, secret);
0reactions
benwoodwardcommented, Jul 13, 2021

Actually found that the const { Webhooks } = new Mux(); throws an error:

Throws Cannot read property 'verifyHeader' of undefined

import Mux from '@mux/mux-node';

const { Webhooks } = new Mux();

// snip

  isValidSignature = Webhooks.verifyHeader(
    JSON.stringify(request.body),
    signature,
    webhookSecret
  );

Works:

import Mux from '@mux/mux-node';

const { Webhooks } = Mux;

// snip

  isValidSignature = Webhooks.verifyHeader(
    JSON.stringify(request.body),
    signature,
    webhookSecret
  );

Second example ↑ is what’s in the README.

See verifyHeader in the README – it will actually raise an exception if the signature is invalid. So you’ll want to wrap it in a try / catch block

Aha, ok thanks 🙂

Instead of doing JSON.stringify(request.body) I would recommend getting access to the raw request body. Stringifying JSON isn’t deterministic in different languages. The signature in mux-signature is created according to the raw request body that is sent over the wire, so in order to verify the signature in a reliable way, you will want to use the raw body instead of the body that has gone through JSON.parse and then JSON.stringify.

Oh, thanks for pointing this out, this code was written with a lot of haste. Yes, looks like rawBody is accessible in Sveltekit endpoint request objects.

Here’s the updated code for my Mux webhook in Sveltekit + Dgraph (in case anyone’s googling this!)

import { dgraphClient } from '$lib/configs/dgraph-client.ts';
import Mux from '@mux/mux-node';

const { Webhooks } = Mux;

const webhookSecret = import.meta.env.VITE_MUX_WEBHOOK_SECRET;

export async function post(request) {
  const signature = request.headers['mux-signature'];
  const txn = dgraphClient.newTxn();

  let isValidSignature = false;

  try {
    isValidSignature = Webhooks.verifyHeader(
      request.rawBody,
      signature,
      webhookSecret
    );

    if (isValidSignature !== true) { throw new Error('Invalid signature') }; // Supposedly not necessary because `.verifyHeader` throws if it doesn't verify

    if (request.body.type === 'video.asset.ready') {
      const playbackId = request.body.data.playback_ids[0].id;
      const uploadId = request.body.data.upload_id;
      const mutationJson = await upsertVideoJson(uploadId, playbackId);
      const videoRecord = await txn.mutate({ mutation: JSON.stringify(mutationJson) });
      const videoRecordId = videoRecord.data.uids.videoRecord;

      await txn.commit();
    };
  } catch(e) {
    if (e === dgraph.ERR_ABORTED) {
      console.log(e)
    } else {
      throw e;
    }
  } finally {
    await txn.discard();

    return {
      body: {
        received: true
      }
    }
  }
}


async function upsertVideoJson(uploadId, playbackId) {
  return {
    query: `{
      var(func: type(Video)) @filter(eq(Video.muxUploadId, \"${uploadId}\")) {
        v as uid
      }
    }`,
    set: [
      {
        "uid": "uid(v)",
        "Video.muxStatus": 'video.asset.ready',
        "Video.muxPlaybackId": playbackId
      }
    ]
  };
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Svelte-Kit Dev Is No Longer Available Use Vite Dev Instead
API Layer: https://apilayer.com/?utm_source=LevelUpTutorials&utm_medium=LeadsAcquisition&utm_content=july22Github PR ...
Read more >
FAQ • SvelteKit
Most issues related to including a library are due to incorrect packaging. Libraries work best with Vite when they distribute an ESM version...
Read more >
Bring @sveltejs/kit/experimental/vite out of experimental #5184
Describe the problem Right now SvelteKit asks users to pass Vite configuration via the kit.vite option in svelte.config.js.
Read more >
svelte - Vite+SvelteKit Build Failing - Stack Overflow
I'm building a website using SvelteKit , scaffolded using pnpm create svelte . However, when I run pnpm build , I get the...
Read more >
Working Sveltekit App w/vite deployed to node server? - Reddit
Can anyone point me to a repo with recent version of Sveltekit that is ... so it's just the client side of Sveltekit...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found