How to enable polyfill in remix config?

1.2k Views Asked by At

(not a dev, begginer building shopify app w/ remix/node.js and learning to code as I go along) So whenever i import { CreatPool } from a MySQL2 file/folder, I get the following error in my npm run dev terminal

"X [ERROR] Node builtin "net" (imported by "node_modules/mysql2/lib/server.js") must be polyfilled for the browser. You can enable this polyfill in your Remix config, e.g. browserNodeBuiltinsPolyfill: { modules: { net: true } } [plugin browser-node-builtins-polyfill-plugin]"

I believe that in this message it tells me exactly how to fix the issue, but i dont understand how to do so. Do I need to add a file/ line of code to browserNodeBuiltinsPolyfill.js? or do I need to run a specific terminal line? I believe the answer is, as I said is this "You can enable this polyfill in your Remix config, e.g. browserNodeBuiltinsPolyfill: { modules: { net: true } } [plugin browser-node-builtins-polyfill-plugin]", but I don't understand it.

tried using mysql instead of mysql2 and the orginal code stopped working so no point.

Any help is greatly appreciated!

1

There are 1 best solutions below

2
On

I'm assuming that you're calling your MySQL functions from your loader/action.

Remix creates two bundles, one for the server and one for the client/browser. Most of the time, Remix is pretty smart and knows which code belongs in each bundle. However, sometimes due to how the package is built, server code can end up in the browser bundle, and vice versa.

Remix has an escape hatch, so you can explicitly state which bundle to use. In your case, it looks like you need to specify that your MySQL code belongs only on the server. You do this by adding the .server suffix to your filename.

// lib/mysql2.server.ts
export function CreatePool() {}
// routes/route.tsx
import { CreatePool } from '~/lib/mysql2.server'

NOTE: If your imports are from a package like mysql2-package, then create the server file like above, but simply re-export the package.

export * from 'mysql2-package'

https://remix.run/docs/en/main/guides/gotchas#server-code-in-client-bundles