Guide on integrating a Web Worker included in an NPM module within a NextJS project

If you're experiencing issues, refer to the Github Repository here: https://github.com/kyledecot/next-worker-bug

Within my NextJS application, there is an NPM package that I have bundled using webpack/ts-loader. This package includes a web Worker & WorkerComponent.

My intention is to use npm install to incorporate this package from npmjs into my NextJS application and utilize the worker as follows:

<App>
  <WorkerComponent />
</App>

Currently, this setup is not functioning properly and generating the following error message:

../worker/lib/index.js (1:1323) @ eval
 ⨯ Error: Automatic publicPath is not supported in this browser
    at eval (../worker/lib/index.js:51:27)
    at eval (../worker/lib/index.js:53:11)
    at eval (../worker/lib/index.js:67:7)
    at eval (../worker/lib/index.js:3:32)
    at eval (../worker/lib/index.js:5:2)
    at (ssr)/../worker/lib/index.js (/Users/tabulous-xyz/Desktop/example/app/.next/server/app/page.js:173:1)
    at __webpack_require__ (/Users/tabulous-xyz/Desktop/example/app/.next/server/webpack-runtime.js:33:42)
    at eval (./src/app/page.tsx:7:64)
    at (ssr)/./src/app/page.tsx (/Users/tabulous-xyz/Desktop/example/app/.next/server/app/page.js:162:1)
    at Object.__webpack_require__ [as require] (/Users/tabulous-xyz/Desktop/example/app/.next/server/webpack-runtime.js:33:42)
    at JSON.parse (<anonymous>)
digest: "3559072519"

https://i.sstatic.net/oktqrjA4.png

I'm uncertain whether this issue is related to NextJS, Webpack, or another factor altogether.

Answer №1

If you're looking to optimize Web Worker bundling, look no further than the workerize-loader tool. This specialized tool is perfect for handling Web Workers within your Next.js application, effectively solving the common issue of "Automatic publicPath is not supported in this browser."

Follow these simple steps to implement this solution:

Step 1: Create a Web Worker file in your NPM package (e.g., my-worker.js)

self.onmessage = function (e) {
  // Your worker code goes here
  self.postMessage('Response from Worker');
};

Step 2: Install the workerize-loader package:

npm install --save-dev workerize-loader

Step 3: Update next.config.js

module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.module.rules.push({
        test: /my-worker\.js$/,
        use: { loader: 'workerize-loader' },
      });
    }
    return config;
  },
};

Step 4: Integrate the Web Worker into your Next.js component:

import Worker from 'my-npm-package/my-worker.js';

const MyComponent = () => {
  const worker = new Worker();

  worker.onmessage = (event) => {
    console.log('Message received from worker:', event.data);
  };

  const handleClick = () => {
    worker.postMessage('Hello, worker!');
  };

  return <button onClick={handleClick}>Run Worker</button>;
};

export default MyComponent;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is your content flickering and constantly re-rendering due to the Next.js router.query?

One issue I'm facing is with a page that relies on router.query to determine the content to display. The problem arises when the page initially renders without any data from router.query, causing a noticeable "flickering" effect once the relevant cod ...

Vercel - Deploying without the need to promote the project

How can I deploy my Nextjs app to production in a way that allows me to run E2E tests on a "pre-prod" version before promoting it to prod, similar to using a preview URL without public traffic being directed there? I am looking for a process where I can v ...

Obtaining AWS Cognito token using AWS Amplify's UI-React

I'm currently developing a Next.js frontend and NestJS backend application, and I am configuring the login component using the @aws-amplify/ui-react library. Following the steps outlined in the documentation here. import { Amplify } from 'aws-amp ...

How can I deploy a react-express application to Azure cloud platform?

Struggling to deploy my react-express application on Azure. The code is divided into client and server directories. Attempted deployment using Azure Static Web application but encountered failure. https://i.stack.imgur.com/ailA0.png https://i.stack.imgur.c ...

Ways to achieve a gradient effect on top of an image

Hey, I'm trying to implement a gradient on images in my project. Here's what I have so far: import Image from 'next/image' import Box from 'mui/material/Box' import PlayIcon from './PlayIcon.tsx' <Box ...

What is the process for uploading an image with express-fileupload?

Looking to upload an image to Cloudinary via Postman using the express-fileupload library for handling multipart forms. Here is a snippet from my index.ts file: import fileUpload from "express-fileupload"; app.use(fileUpload()); In my controller ...

Dynamic content in NextJS: First, statically render a page and then customize it with user-specific data

I need advice on how to handle a specific data fetching scenario with NextJS static page rendering. We have a page that showcases articles, similar to this example. The content is the same for all users (perfect for static rendering), but lock icons should ...

Is there a way to prevent certain folders that have .vue files from being included in the VueJS build process?

https://i.sstatic.net/YU1rB.png module.exports = { presets: [ '@vue/app' ], module:{ rules: [ { test: /\.vue$/, exclude: [ './src/components/Homepages/number1', './src ...

Angular 8 Issue: Absence of _body and Headers in Response

Our back-end code is written in C# within the .NET environment, targeting the 4.6.1 framework. Recently, our front-end was upgraded from Angular 4 to Angular 8. During this upgrade, webpack transitioned from version 2.3 to version 4.41 and typescript from ...

Encountering a Laravel 9 error: TypeError with webpack-cli - compiler.plugin is not a valid function

I recently downloaded a Laravel 9 template and have been attempting to run and utilize it. However, I keep encountering an issue every time I try running npm run dev. The error message that appears is [webpack-cli] TypeError: compiler.plugin is not a fun ...

Is it possible to define multiple regular expressions for a single field using yup in a form validation?

My goal is to validate an input to only accept URLs in Google Maps format. There are three possible valid outputs for a Google Maps URL: (for Google Maps app) (I only want to focus on ) (when sharing directly from Google Maps) Currently, I am able to ...

Condense styles and templates into inline format using Angular-cli

Can anyone help me with configuring angular-cli to support inlining of css and html resources during the build process? I am currently using angular-cli version 1.0.0-beta.24. I attempted building with both ng buld and ng build --env=prod --target=product ...

Unexpected TypeError when using Response.send()

Here is a snippet of my simple express code: const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) In my development environmen ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

During the build process, the parameters in Next.js are not accessible

I am currently using Next.js 13 with the experimental app directory. My application utilizes dynamic routing in the following format: https://app.domain/[itemid]/[slug] Within my [slug] directory, if I create a server-side route file pages.jsx with th ...

Leveraging the power of Next.js version 13 in tandem with Elastic

I can't seem to figure out why I am getting an error when trying to read from an existing index using this API route and client-side page setup: import { Client } from "@elastic/elasticsearch"; import { NextResponse } from "next/server& ...

What is the best way to store information in JSON format and transmit it to a server using an API?

I'm looking to save the form data in JSON format and send it from my UI to the server. I've searched through numerous sources but haven't found a solution yet. Struggling with the basic design structure, any help would be greatly appreciat ...

Dynamic routing in Next.js with express leads to the refreshing of the page

I am facing an issue with my Next.js blog application that I built using an express custom browser. Whenever I click on a Link to route to '/blog/article-1', the page refreshes upon arrival at the destination. How can I prevent this from happenin ...