Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: SharedArrayBuffer is not defined #263

Open
avi12 opened this issue Oct 2, 2021 · 42 comments
Open

ReferenceError: SharedArrayBuffer is not defined #263

avi12 opened this issue Oct 2, 2021 · 42 comments

Comments

@avi12
Copy link
Contributor

avi12 commented Oct 2, 2021

Describe the bug
Getting a ReferenceError: SharedArrayBuffer is not defined error after [info] ffmpeg-core.js script loaded

To Reproduce
Simply initialize FFmpeg on Firefox

Expected behavior
It should work as usual on Firefox, but it cannot properly initialize

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10 x64 21H1
  • Browser: Firefox 92.0.1

Additional context
This is my repository

@RSWilli
Copy link

RSWilli commented Oct 6, 2021

as the Readme states:

SharedArrayBuffer is only available to pages that are cross-origin isolated. So you need to host your own server with Cross-Origin-Embedder-Policy: require-corp and Cross-Origin-Opener-Policy: same-origin headers to use ffmpeg.wasm.

SharedArrayBuffer is not available until you do add these headers

and in Safari it will never be available, because SharedArrayBuffer is disabled there

https://caniuse.com/sharedarraybuffer

@avi12
Copy link
Contributor Author

avi12 commented Oct 6, 2021

The reason I made my browser extension in the first place is that it doesn't need a server to work but instead use the user's computational power

@MemoryAndDream
Copy link

as the Readme states:

SharedArrayBuffer is only available to pages that are cross-origin isolated. So you need to host your own server with Cross-Origin-Embedder-Policy: require-corp and Cross-Origin-Opener-Policy: same-origin headers to use ffmpeg.wasm.

SharedArrayBuffer is not available until you do add these headers

and in Safari it will never be available, because SharedArrayBuffer is disabled there

https://caniuse.com/sharedarraybuffer

I add these headers when getting my html page and it works.But now I have trouble with add third party JS in my page,which will be blocked by cross-origin isolated. Any work around method to use third party JS in my video edit page(with wasm)?

@donatj
Copy link

donatj commented Oct 15, 2021

Dumb question from someone who knows nothing - what would it take / would it even be possible to rewrite this not to use SharedArrayBuffer?

Given the current state of how difficult it is to use, seems like if it's possible, it'd be worth it.

@avi12
Copy link
Contributor Author

avi12 commented Oct 15, 2021

Even if you manage to rewrite it in a different way, I doubt the progress of releases
A couple of pull requests have been merged (including my #232), but the last release was on June 14

@Fanna1119
Copy link

If there is someone using vite for development environment.
https://github.com/chaosprint/vite-plugin-cross-origin-isolation

@Zophiel
Copy link

Zophiel commented Dec 2, 2021

@Fanna1119 This doesn't solve the issue in a live environment

@martins-a
Copy link

martins-a commented Jan 7, 2022

Hello, in react easier way is using this library: https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually

With this you can create a proxy, in the proxy you will be able to set the headers, example bellow:

module.exports = function (app) {
    app.use(function (req, res, next) {
        res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
        res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
        next();
    });

    app.use(
        '/api',
        createProxyMiddleware({
          target: 'http://localhost:8080',
          changeOrigin: true,
        })
      );
};

I really don't know how to deal with this in SPAs production env, but for server-client applications it should work fine (for example react SSR).

zeek0x added a commit to zeek0x/emogif that referenced this issue Feb 18, 2022
zeek0x added a commit to zeek0x/emogif that referenced this issue Feb 18, 2022
camelcrush referenced this issue in camelcrush/wetube-clone Feb 22, 2022
@zack-pronto
Copy link

Safari now has support for SharedArrayBuffer as of March 2022 https://caniuse.com/sharedarraybuffer

@usr-ein
Copy link

usr-ein commented Jun 7, 2022

Hello, in react easier way is using this library: https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually

With this you can create a proxy, in the proxy you will be able to set the headers, example bellow:

I had to tune your example for it to work with React. Beware that even when running a Typescript react project, you need to write this as a setupProxy.JS (and not .TS):

module.exports = function (app) {
    app.use(function (req, res, next) {
        res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
        res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
        next();
    });
};

For SPAs, you don't need to create a proxy middleware, you just need to intercept the req/resp and add your headers.

Also, you don't need to install http-proxy-middleware at all for this to work. It just works straight out of the box on React apps.

Why we need those headers, according to the doc.

@hankchiutw
Copy link

For developing in vite, you can set the vite.config.js:

export default {
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
};

@SeiwonPark
Copy link

SeiwonPark commented Jun 30, 2022

Anyone who's using Next.js,

here's my next.config.js file and it works perfectly

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  async headers() {
    return [
      {
        source: '/',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'require-corp',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

@filmo
Copy link

filmo commented Jul 18, 2022

I've created a setupProxy.js file for my React app, and have installed http-proxy-middleware suggested on the link, but the following code doesn't seem to work for me.

module.exports = function (app) {
    app.use(function (req, res, next) {
        res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
        res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
        next();
    });
};

It doesn't seem like this module.exports is getting called when I run npm start I continue to get the error Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined.

I'm trying to follow along this React/ffmpeg WASM tutorial. I'm using Chrome 103, ffmpeg wasm 0.10.0, snowpack 2.1, react 17.0.2

@khaled-shaaban
Copy link

as the Readme states:

SharedArrayBuffer is only available to pages that are cross-origin isolated. So you need to host your own server with Cross-Origin-Embedder-Policy: require-corp and Cross-Origin-Opener-Policy: same-origin headers to use ffmpeg.wasm.

SharedArrayBuffer is not available until you do add these headers

and in Safari it will never be available, because SharedArrayBuffer is disabled there

https://caniuse.com/sharedarraybuffer

It is now available though, no?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#browser_compatibility

@cleandevcode
Copy link

module.exports = function (app) {
    app.use(function (req, res, next) {
        res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
        res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
        next();
    });
};

It is working on my side (React : 17.0.2, ffmpeg wasm: 0.10.3, chrome 103), but all the social logins (google, Microsoft, apple) does not work. All return the error saying pop up is closed by user.

Will be any solutions?

@kiradea
Copy link

kiradea commented Jan 17, 2023

anyone use UmiJS ?

@donsaale5722
Copy link

Permanant solution of Shared Array buffer is not define in react js when i am include fbsdk in my project

#484 #483 #190 #482 #402 #121 #469

@hlp-pls
Copy link

hlp-pls commented Apr 20, 2023

for someone working with php, writing this code to the php file that contains the html document worked for me.

<?php
header("Cross-Origin-Embedder-Policy: require-corp");
header("Cross-Origin-Opener-Policy: same-origin");
?>

@AlRodriguezGar14
Copy link

Has anyone found a solution for Nuxt 3? It did not manage to overcome this issue.

Whenever I load ffmpeg, I get the error, and establishing these headers did not help.
f1f71c-7747-4977-969e-ea0d6790910b:22 Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined at b2f1f71c-7747-4977-969e-ea0d6790910b:22:175 at Object.load (createFFmpeg.js:117:20) at async load (app.vue:15:3) (

@SrLeet03
Copy link

SrLeet03 commented Jul 1, 2023

For next js ,having following type of config worked for me.

`/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async headers() {
return [
{
source: '/',
headers: [
{
key: 'Cross-Origin-Embedder-Policy',
value: 'require-corp',
},
{
key: 'Cross-Origin-Opener-Policy',
value: 'same-origin',
},
],
},
]
}

webpack(config, { webpack }) {
config.module.rules.push({
test: /.svg$/,
use: ['@svgr/webpack'],
})

config.plugins.push(
  new webpack.IgnorePlugin({
    resourceRegExp: /^\.\/wordlists\/(?!english)/,
    contextRegExp: /bip39\/src$/,
  })
)

config.resolve.alias = {
  ...config.resolve.alias,
  assets: getSharedPath('assets'),
  components: getSharedPath('components'),
  containers: getSharedPath('containers'),
  layouts: getSharedPath('layouts'),
  lib: getSharedPath('lib'),
  screens: getSharedPath('screens'),
  store: getSharedPath('store'),
  styles: getSharedPath('styles'),
}

return config

}
env: {

},
}

module.exports = nextTranslate(withTM(withPWA(nextConfig)))`

@tgraupmann
Copy link

tgraupmann commented Jul 12, 2023

All the sudden, like right now, the headers are not enough. There's an experimental Chrome flag but even that doesn't expose the SharedMemoryBuffer. It worked yesterday and even 10 minutes ago...

image

This WAS my workaround - https://vercel.com/guides/fix-shared-array-buffer-not-defined-nextjs-react

I have all the headers set via php. I confirmed the headers were set in the response.

header("Cross-Origin-Opener-Policy: same-origin");
header("Cross-Origin-Embedder-Policy: require-corp");

Broken in Edge/Chrome.

Firefox is still okay.

WebView2 browser is okay - https://learn.microsoft.com/en-us/microsoft-edge/webview2/samples/webview2browser?source=recommendations

I restarted my Chrome and the issue seems to have gone away. So I'm not sure what caused it. It's just odd that Chrome/Edge had the issue at the same time.

@nibk
Copy link

nibk commented Jul 13, 2023

I had the same issue just start recently on a Chrome 114 build using a different wasm project. Previously I had NOT enabled:

Cross-Origin-Opener-Policy

I only enabled

Cross-Origin-Embedder-Policy

and everything worked. Now the Opener policy seems to be required also.

@dataexcess
Copy link

Has anyone found a solution for Nuxt 3? It did not manage to overcome this issue.

Whenever I load ffmpeg, I get the error, and establishing these headers did not help. f1f71c-7747-4977-969e-ea0d6790910b:22 Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined at b2f1f71c-7747-4977-969e-ea0d6790910b:22:175 at Object.load (createFFmpeg.js:117:20) at async load (app.vue:15:3) (

I am also using nuxt 3. DId you find a solution for this?

@AlRodriguezGar14
Copy link

Has anyone found a solution for Nuxt 3? It did not manage to overcome this issue.
Whenever I load ffmpeg, I get the error, and establishing these headers did not help. f1f71c-7747-4977-969e-ea0d6790910b:22 Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined at b2f1f71c-7747-4977-969e-ea0d6790910b:22:175 at Object.load (createFFmpeg.js:117:20) at async load (app.vue:15:3) (

I am also using nuxt 3. DId you find a solution for this?

Sadly not @dataexcess. I had to move to React to make it work.

@dataexcess
Copy link

Has anyone found a solution for Nuxt 3? It did not manage to overcome this issue.
Whenever I load ffmpeg, I get the error, and establishing these headers did not help. f1f71c-7747-4977-969e-ea0d6790910b:22 Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined at b2f1f71c-7747-4977-969e-ea0d6790910b:22:175 at Object.load (createFFmpeg.js:117:20) at async load (app.vue:15:3) (

I am also using nuxt 3. DId you find a solution for this?

Sadly not @dataexcess. I had to move to React to make it work.

Hey! Using this nuxt plugin "nuxt-security" fixed it for me ! :D

https://snyk.io/blog/adding-security-to-nuxt-3/

@tgraupmann
Copy link

tgraupmann commented Jul 14, 2023

I can still reproduce the issue. If you use a lot of memory by using a canvas element and capture a lot of frames with getImageData into memory, somehow the added memory knocks out the settings. And even if both headers are present you get the SharedMemoryBuffer error.

image

I thought the workaround was to kill all your browser instances and relaunch. But it still happens so I have to use one of the browsers that still works.

Hmmm Firefox is showing duplicate headers, that might be the problem.

image

I had a .htaccess adding the headers and php adding the headers. So if you have a duplicate header it is discarded and SharedMemoryBuffer goes away.

After I fixed the duplicate header issue, it's working normally.

@gabrielstuff
Copy link
Contributor

For anyone trying to find a solution when hosting on netlify for instance, you can use : https://github.com/gzuidhof/coi-serviceworker which makes it available.

@iAmInActions
Copy link

So, ive run into this issue too now. I added the stuff to my htaccess but its not working. When running the included example server on my local machine it works but when running it on my remote system under apache2, firefox keeps complaining. I have tried putting it in the .htaccess, in php and even tried writing it from javascript after the page loaded (which doesnt work btw but still tried it because i am really desperate to get this working). For htaccess and php it shows up in firefox when looking at the header but the browser seems to just ignore it and throws the error anyways. The same happens in chrome too. If anyone can help me out with that id be really thankful.

@Bessonov
Copy link

I think this issue could be closed because there are multiple solutions presented. According to the third point in https://caniuse.com/?search=SharedArrayBuffer, this is the way to enable support. If this doesn't work for your browser, consider opening an issue in the browser's issue tracker.

@jumpjack
Copy link

jumpjack commented Mar 4, 2024

How to solve this issue using Github Pages?

@WesleyBatista
Copy link
Contributor

How to solve this issue using Github Pages?

@jumpjack, out of curiosity specifically to the Github Pages deployment part, I tried out the vanilla-app version and it worked "out of the box": https://wesleybatista.github.io/ffmpeg.wasm-gh-pages/trim.html - source

Regarding original issue, maybe it's worth mentioning that headers solution above also worked for me, deploying an sveltekit app using firebase. Wonky setup, but working. Demo

@jumpjack
Copy link

jumpjack commented Mar 6, 2024

It does not work "out of the box" for me, forking and enabling pages is not enough, needed files are not found.
I tried manual downloadin and unpacking and storing in my github folders, but ffmpeg.wasm is >25MB so I can't upload by browser.
Maybe I should run a github action? I have no idea about how they work.

@CodyBontecou
Copy link

For developing in vite, you can set the vite.config.js:

export default {
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
};

This doesn't seem to be working anymore, at least when hosting on Vercel.

@smithmich12
Copy link

For developing in vite, you can set the vite.config.js:

export default {
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
};

This doesn't seem to be working anymore, at least when hosting on Vercel.

I was able to get this to work with vite by adding a vercel.json file to the root folder of my project. I am now running into different issues but my SharedArrayBuffer error is gone on vercel now.

{
    "headers": [
        {
            "source": "/(.*)",
            "headers": [
                { 
                    "key": "Cross-Origin-Embedder-Policy",
                    "value": "require-corp"
                },
                {
                    "key": "Cross-Origin-Opener-Policy", 
                    "value": "same-origin"
                }
            ]
        }
    ]
}

@syjf
Copy link

syjf commented Apr 18, 2024

要在 vite 中开发,您可以设置vite.config.js:

export default {
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
};

After adding, the iframe and server images cannot be accessed. How can I solve this problem

@marwie
Copy link

marwie commented Jun 11, 2024

要在 vite 中开发,您可以设置vite.config.js:

export default {
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
};

After adding, the iframe and server images cannot be accessed. How can I solve this problem

This might help you: https://blog.stackblitz.com/posts/cross-browser-with-coop-coep/

If CORS is enabled on external resources like images, scripts, stylesheets or videos, 
they have to be explicitly loaded by using the [crossorigin](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin) attribute. 
The default value for this attribute is anonymous, which means that credentials such as cookies or http authentication will only be sent if the resources are fetched from the same origin. 
If the image is loaded from a different origin, all information is stripped so that only information publicly available is sent between client and server.

try <img crossorigin="anonymous" src="..." />

@nica0012
Copy link

I am having the same issue as well, i am using vite and am hosting my project on cpanel. It seems with the vite config setting the headers I am able to make it work on desktop, but not mobile.

On mobile browsers it works by setting the cors headers in my htaccess file, but when I do this I can no longer load data from my third party libraries.

I've been stuck on this issue for 2 weeks now trying to get into prod...

@subham827
Copy link

as the Readme states:

SharedArrayBuffer is only available to pages that are cross-origin isolated. So you need to host your own server with Cross-Origin-Embedder-Policy: require-corp and Cross-Origin-Opener-Policy: same-origin headers to use ffmpeg.wasm.

SharedArrayBuffer is not available until you do add these headers
and in Safari it will never be available, because SharedArrayBuffer is disabled there
https://caniuse.com/sharedarraybuffer

I add these headers when getting my html page and it works.But now I have trouble with add third party JS in my page,which will be blocked by cross-origin isolated. Any work around method to use third party JS in my video edit page(with wasm)?

Please do share any other work around

@gazreyn
Copy link

gazreyn commented Jun 30, 2024

Has anyone found a solution for Nuxt 3? It did not manage to overcome this issue.
Whenever I load ffmpeg, I get the error, and establishing these headers did not help. f1f71c-7747-4977-969e-ea0d6790910b:22 Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined at b2f1f71c-7747-4977-969e-ea0d6790910b:22:175 at Object.load (createFFmpeg.js:117:20) at async load (app.vue:15:3) (

I am also using nuxt 3. DId you find a solution for this?

Sadly not @dataexcess. I had to move to React to make it work.

Hey! Using this nuxt plugin "nuxt-security" fixed it for me ! :D

https://snyk.io/blog/adding-security-to-nuxt-3/

For anyone using Nuxt 3, you need to set headers for both nuxt routes and for vite

For example

export default defineNuxtConfig({
  routeRules: {
    '/**': {
      headers: {
        'Cross-Origin-Opener-Policy': 'same-origin',
        'Cross-Origin-Embedder-Policy': 'require-corp',
      },
    },
  },
  vite: {
    optimizeDeps: {
      exclude: ['@ffmpeg/ffmpeg', '@ffmpeg/util'],
    },
    server: {
      headers: {
        'Cross-Origin-Opener-Policy': 'same-origin',
        'Cross-Origin-Embedder-Policy': 'require-corp',
      },
    },
  },
});

@omitchen
Copy link

omitchen commented Oct 6, 2024

Anyone who's using Next.js,

here's my next.config.js file and it works perfectly

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  async headers() {
    return [
      {
        source: '/',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'require-corp',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

it's not work new, Next 13.2.1 + chrome 126 + cf deploy, localhost is OK? who can help me
image

@jasonz1987
Copy link

Anyone who's using Next.js,
here's my next.config.js file and it works perfectly

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  async headers() {
    return [
      {
        source: '/',
        headers: [
          {
            key: 'Cross-Origin-Embedder-Policy',
            value: 'require-corp',
          },
          {
            key: 'Cross-Origin-Opener-Policy',
            value: 'same-origin',
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

it's not work new, Next 13.2.1 + chrome 126 + cf deploy, localhost is OK? who can help me image

it's also not working on nextjs 14.2

@saradotdev
Copy link

This worked for me too for vercel. Thanks a ton!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests