eslint-plugin-ssr-friendly

raw JSON →
1.3.0 verified Sat Apr 25 auth: no javascript

ESLint plugin that detects incorrect use of DOM globals (e.g., window, document, navigator) in module scope, constructors, React component render methods, and function components, ensuring code is safe for server-side rendering (SSR) and Node.js environments. Stable version 1.3.0 as of August 2023. It focuses on preventing runtime errors during SSR by catching patterns that assume a browser environment. Unlike general linting rules, it provides specific rules for React class components, function components, and class constructors. Released under MIT license with monthly releases.

error Definition for rule 'ssr-friendly/no-dom-globals-in-module-scope' was not found.
cause The plugin is not installed or not listed in the 'plugins' array.
fix
Ensure 'eslint-plugin-ssr-friendly' is installed and added to plugins: ['ssr-friendly'].
error ESLint couldn't find the plugin "eslint-plugin-ssr-friendly".
cause The plugin package is missing from node_modules.
fix
Run 'npm install --save-dev eslint-plugin-ssr-friendly'.
gotcha The plugin only detects direct use of DOM globals in certain scopes; it does not catch indirect access via helper functions or properties.
fix Manually review code that accesses DOM globals through functions or variables.
gotcha Rules cannot verify that DOM globals used inside functions are guarded by a typeof check. For example, 'const isRetina = () => devicePixelRatio >= 2' is allowed even if called unconditionally.
fix Ensure all uses of DOM globals in functions are guarded with 'if (typeof window !== "undefined")'.
deprecated The 'recommended' config may change between minor versions; pin your eslint-plugin-ssr-friendly version to avoid unexpected rule changes.
fix Specify exact version in package.json (e.g., "eslint-plugin-ssr-friendly": "1.3.0") and review changelog before upgrading.
npm install eslint-plugin-ssr-friendly
yarn add eslint-plugin-ssr-friendly
pnpm add eslint-plugin-ssr-friendly

Quick setup using recommended config; shows how to enable all rules and example violations.

// Install the plugin
// npm install --save-dev eslint-plugin-ssr-friendly

// In .eslintrc.js
module.exports = {
  plugins: ['ssr-friendly'],
  extends: ['plugin:ssr-friendly/recommended'],
  rules: {
    'ssr-friendly/no-dom-globals-in-module-scope': 'error',
    'ssr-friendly/no-dom-globals-in-constructor': 'error',
    'ssr-friendly/no-dom-globals-in-react-cc-render': 'error',
    'ssr-friendly/no-dom-globals-in-react-fc': 'error',
  },
};

// Example code that will trigger errors:
// const width = window.innerWidth; // module scope error
// class MyComp extends React.Component {
//   render() { return <div>{window.innerWidth}</div>; } // render error
// }