Recently, I came across this SharedArrayBuffer is not defined error in the Firefox browser, while working on my react app called Giferate. This error was hitting in the Firefox, mobile browsers while my app worked just fine on the Chrome desktop version.
What is SharedArrayBuffer ?
SharedArrayBuffer is an array object in JavaScript, which can hold raw bytes and the memory contents can be shared between multiple threads. There is another array object called ArrayBuffer in JavaScript, which can be used to read and write raw byte data but it doesn’t allow shared access. In multi threaded functionality, SharedArrayBuffer are more efficient option.
So why SharedBufferArray not defined error ?
With some googling, I found this – With the discovery of meltdown attack spectre, many browsers including Firefox have disabled ‘sharedArrayBuffer’ and few other powerful browser functionalities. While Chrome allows using it for now but starting the Chrome 92 version, it will disable it as well. And to enable it in the browser, we have to make our website ‘Cross-Origin-Isolation‘.
How to fix SharedArrayBuffer not defined error ?
As per this guide, the requirement is to add following two headers to the top level document of your website:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
We should be able to add these headers via a web server like Nginx or Apache.
My approach to fix this issue ?
So, I decided to Dockerize my react app and host it separately with these two headers added to its Nginx server, like this
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
add_header 'Cross-Origin-Opener-Policy' 'same-origin';
}
#error_page 404 /404.html;
}
Above is an excerpt from the default.conf file in the Nginx server. I just added those two headers under location directive for ‘/’.
And Voila !! It fixed the issue and I can use my app even on Firefox and mobile browsers as well 😉
There is additional benefit with this approach, i.e its localised to my web app only. And therefore doesn’t break any other functionalities on my website.
By the way, do checkout this other post How to enable SharedArrayBuffer on WordPress website in case you want to make your WordPress website CrossOriginIsolated.
Nice
How can I do that with a static website?
Thanks!
This approach will even work for static website. If you have the access to the hosting server then you can easily add headers to the web server directly or can edit to the containerised (Docker/Kubernetes) app instead.
Tengo este mismo error en un proyecto angular usando un SDK de react, cómo lo podrÃa solucionar?
Are you hosting your React app on some cloud server like AWS, GCP etc ? Can you tell me more about your setup where you are facing the issue ?