Run the library in server-side environment (Next.js)
Hello, I have a problem using my library (packed by rollup) in my Next/React application, I have this error : ReferenceError: window is not defined
Call Stack eval webpack-internal:///../library/lib/cjs/index.js (23014:15)
And the code in that line is : var browser = window.DOMPurify || (window.DOMPurify = requirePurify().default || requirePurify());
it's due to Next.js is trying to server-side render my library but can't find the "window" reference, here is my rollup config file, how can I make it rendable in next.js :
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import json from "@rollup/plugin-json";
import postcss from "rollup-plugin-postcss";
import terser from '@rollup/plugin-terser';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
const packageJson = require("./package.json");
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
peerDepsExternal(),
resolve({
browser: true
}),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
json(),
postcss(),
terser()
],
},
{
input: "lib/esm/types/index.d.ts",
output: [
{
file: 'lib/index.d.ts',
format: 'esm',
}
],
plugins: [dts()],
external: ['react', 'react-dom', /\.css$/]
},
];
The issue needs to be fixed in your code. Wherever you're using browser-specific APIs, you need to verify if they even exist before accessing them
@brc-dd do you mean the "library" code or the consuming "application" code ?
The library code.
I don't have that in my code, it's rollup who is generating this line :
var browser = window.DOMPurify || (window.DOMPurify = requirePurify().default || requirePurify());
in lib/cjs/index.js
Can you share a minimal example that we can reproduce (preferably in the form of a repo link)? It is likely that one of your dependency has that part of code 👀
@rm116 Did you ever get this resolved? I'm running into the same issue.