How can I fix SharedArrayBuffer is not defined?

SharedArrayBuffer is a JavaScript construct that allows two or more JavaScript contexts, such as multiple web workers or the main thread, to read and write to a shared memory block. This facilitates parallel processing and efficient data transfer in web applications.

Why is SharedArrayBuffer not defined?

In response to potential security vulnerabilities like the Spectre attack, which could exploit high-resolution timers like SharedArrayBuffer to read memory across origins, SharedArrayBuffer was disabled by default from Chrome 92 onwards.

How can I fix SharedArrayBuffer not defined?

You can resolve this issue in one of two ways.

Enable cross-origin isolation

Cross-origin isolation is a security feature that prevents documents from different origins from sharing resources, thereby reducing the risk of side-channel attacks like Spectre.

To enable cross-origin isolation, send two HTTP headers. If you're using Next.js, you can use next.config.js:

next.config.js
module.exports = {
async headers() {
return [
{
source: '/',
headers: [
{
key: 'Cross-Origin-Embedder-Policy',
value: 'require-corp',
},
{
key: 'Cross-Origin-Opener-Policy',
value: 'same-origin',
},
],
},
];
},
};
Setting the proper headers to enable cross-origin isolation.

Or alternatively, with vercel.json:

vercel.json
{
"headers": [
{
"source": "/",
"headers": [
{
"key": "Cross-Origin-Embedder-Policy",
"value": "require-corp"
},
{
"key": "Cross-Origin-Opener-Policy",
"value": "same-origin"
}
]
}
]
}
Setting the proper headers to enable cross-origin isolation.
  • Cross-Origin-Embedder-Policy: require-corp ensures that resources loaded on your document are isolated to your origin and won't be shared with other sites.
  • Cross-Origin-Opener-Policy: same-origin ensures that your document doesn't share the same process with other documents unless they're from the same origin.

For more information on cross-origin isolation, read this guide.

Join an origin trial (if available)

As of Chrome 92, you can opt your site into an origin trial for SharedArrayBuffer. However, note that the availability and conditions of these trials may change over time. Check the current status of origin trials at chrome://flags/#enable-sharedarraybuffer-origin-trial. After registering, you may need to restart Chrome for the changes to take effect.

Conclusion

SharedArrayBuffer can significantly enhance the performance of your web applications. However, due to potential security risks, using it requires careful implementation. By following the steps above, you can safely leverage SharedArrayBuffer in your web applications.

Couldn't find the guide you need?