Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

misc: add internal lint rule against usage of typeof window #40614

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion .eslintrc.json
@@ -1,7 +1,13 @@
{
"root": true,
"parser": "@babel/eslint-parser",
"plugins": ["react", "react-hooks", "jest", "import"],
"plugins": [
"react",
"react-hooks",
"jest",
"import",
"@next/eslint-plugin-private-next"
],
"env": {
"browser": true,
"commonjs": true,
Expand Down Expand Up @@ -182,6 +188,12 @@
],
"eslint-plugin/require-meta-docs-url": "error"
}
},
{
"files": ["packages/next/**/*.js", "packages/next/**/*.ts"],
"rules": {
"@next/private-next/no-typeof-window": "error"
}
}
],
"rules": {
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -67,6 +67,7 @@
"@next/polyfill-module": "workspace:*",
"@next/polyfill-nomodule": "workspace:*",
"@next/swc": "workspace:*",
"@next/eslint-plugin-private-next": "workspace:*",
"@svgr/webpack": "5.5.0",
"@swc/cli": "0.1.55",
"@swc/core": "1.2.203",
Expand Down
5 changes: 5 additions & 0 deletions packages/eslint-plugin-private-next/index.js
@@ -0,0 +1,5 @@
module.exports = {
rules: {
'no-typeof-window': require('./rules/no-typeof-window.js'),
},
}
22 changes: 22 additions & 0 deletions packages/eslint-plugin-private-next/package.json
@@ -0,0 +1,22 @@
{
"name": "@next/eslint-plugin-private-next",
"version": "1.0.0",
"private": true,
"description": "Private ESLint plugin for the Next.js repo.",
"main": "index.js",
"license": "MIT",
"repository": {
"url": "vercel/next.js",
"directory": "packages/eslint-plugin-private-next"
},
"devDependencies": {
"eslint": "7.24.0"
},
"peerDependencies": {
"eslint": ">=0.8.0"
},
"files": [
"index.js",
"rules"
]
}
70 changes: 70 additions & 0 deletions packages/eslint-plugin-private-next/rules/no-typeof-window.js
@@ -0,0 +1,70 @@
// A lint rule that disallows the use of typeof window !== 'undefined' in Next.js code with a suggestion to use process.env.browser instead.

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow typeof window !== "undefined"',
category: 'Possible Errors',
recommended: true,
url: 'https://nextjs.org/docs/messages/no-typeof-window',
},
fixable: 'code',
messages: {
noTypeofWindow: `For proper dead code elimination, do not use \`typeof window\`to check if the code is running in the browser. Use \`process.env.browser\` instead.`,
},
},
create(context) {
return {
BinaryExpression(node) {
if (
node.operator !== '!==' &&
node.operator !== '===' &&
node.operator !== '!=' &&
node.operator !== '=='
) {
return
}

if (
(node.left?.type !== 'UnaryExpression' ||
node.left?.operator !== 'typeof') &&
(node.right?.type !== 'UnaryExpression' ||
node.right?.operator !== 'typeof')
) {
return
}

if (
(node.right?.type !== 'Literal' ||
node.right?.value !== 'undefined') &&
(node.left?.type !== 'Literal' || node.left?.value !== 'undefined')
) {
return
}

if (
(node.left.argument?.type !== 'Identifier' ||
node.left.argument?.name !== 'window') &&
(node.right.argument?.type !== 'Identifier' ||
node.right.argument?.name !== 'window')
) {
return
}

const isNegated = node.operator === '!==' || node.operator === '!='

context.report({
node,
messageId: 'noTypeofWindow',
fix(fixer) {
return fixer.replaceText(
node,
`${isNegated ? '' : '!'}process.env.browser`
)
},
})
},
}
},
}
@@ -0,0 +1,61 @@
const rule = require('./no-typeof-window')
// this is a dev file
// eslint-disable-next-line import/no-extraneous-dependencies
const { RuleTester } = require('eslint')

const ruleTester = new RuleTester()

const errors = [{ messageId: 'noTypeofWindow' }]

ruleTester.run('no-typeof-window', rule, {
valid: [
{
code: 'process.env.browser',
},
{
code: '!process.env.browser',
},
],
invalid: [
{
code: 'typeof window !== "undefined"',
errors,
output: 'process.env.browser',
},
{
code: 'typeof window === "undefined"',
errors,
output: '!process.env.browser',
},
{
code: '"undefined" !== typeof window',
errors,
output: 'process.env.browser',
},
{
code: '"undefined" === typeof window',
errors,
output: '!process.env.browser',
},
{
code: 'typeof window != "undefined"',
errors,
output: 'process.env.browser',
},
{
code: 'typeof window == "undefined"',
errors,
output: '!process.env.browser',
},
{
code: '"undefined" != typeof window',
errors,
output: 'process.env.browser',
},
{
code: '"undefined" == typeof window',
errors,
output: '!process.env.browser',
},
],
})
3 changes: 1 addition & 2 deletions packages/next/client/router.ts
@@ -1,4 +1,3 @@
/* global window */
import React from 'react'
import Router from '../shared/lib/router/router'
import type { NextRouter } from '../shared/lib/router/router'
Expand All @@ -22,7 +21,7 @@ const singletonRouter: SingletonRouterBase = {
readyCallbacks: [],
ready(cb: () => void) {
if (this.router) return cb()
if (typeof window !== 'undefined') {
if (process.env.browser) {
this.readyCallbacks.push(cb)
}
},
Expand Down
2 changes: 1 addition & 1 deletion packages/next/client/trusted-types.ts
Expand Up @@ -9,7 +9,7 @@ let policy: TrustedTypePolicy | null | undefined
* here or set to null if Trusted Types is not supported in the browser.
*/
function getPolicy() {
if (typeof policy === 'undefined' && typeof window !== 'undefined') {
if (typeof policy === 'undefined' && process.env.browser) {
policy =
window.trustedTypes?.createPolicy('nextjs', {
createHTML: (input) => input,
Expand Down
6 changes: 3 additions & 3 deletions packages/next/shared/lib/loadable.js
Expand Up @@ -94,12 +94,12 @@ function createLoadableComponent(loadFn, options) {
}

// Server only
if (typeof window === 'undefined') {
if (!process.env.browser) {
ALL_INITIALIZERS.push(init)
}

// Client only
if (!initialized && typeof window !== 'undefined') {
if (!initialized && process.env.browser) {
// require.resolveWeak check is needed for environments that don't have it available like Jest
const moduleIds =
opts.webpack && typeof require.resolveWeak === 'function'
Expand Down Expand Up @@ -296,7 +296,7 @@ Loadable.preloadReady = (ids = []) => {
})
}

if (typeof window !== 'undefined') {
if (process.env.browser) {
window.__NEXT_PRELOADREADY = Loadable.preloadReady
}

Expand Down
6 changes: 3 additions & 3 deletions packages/next/shared/lib/router/router.ts
Expand Up @@ -592,7 +592,7 @@ type HistoryMethod = 'replaceState' | 'pushState'

const manualScrollRestoration =
process.env.__NEXT_SCROLL_RESTORATION &&
typeof window !== 'undefined' &&
process.env.browser &&
'scrollRestoration' in window.history &&
!!(function () {
try {
Expand Down Expand Up @@ -972,7 +972,7 @@ export default class Router implements BaseRouter {

this._initialMatchesMiddlewarePromise = Promise.resolve(false)

if (typeof window !== 'undefined') {
if (process.env.browser) {
// make sure "as" doesn't start with double slashes or else it can
// throw an error as it's considered invalid
if (!as.startsWith('//')) {
Expand Down Expand Up @@ -2176,7 +2176,7 @@ export default class Router implements BaseRouter {
asPath: string = url,
options: PrefetchOptions = {}
): Promise<void> {
if (typeof window !== 'undefined' && isBot(window.navigator.userAgent)) {
if (process.env.browser && isBot(window.navigator.userAgent)) {
// No prefetches for bots that render the link since they are typically navigating
// links via the equivalent of a hard navigation and hence never utilize these
// prefetches.
Expand Down
4 changes: 2 additions & 2 deletions packages/next/shared/lib/router/utils/parse-relative-url.ts
Expand Up @@ -21,13 +21,13 @@ export function parseRelativeUrl(
base?: string
): ParsedRelativeUrl {
const globalBase = new URL(
typeof window === 'undefined' ? 'http://n' : getLocationOrigin()
!process.env.browser ? 'http://n' : getLocationOrigin()
)

const resolvedBase = base
? new URL(base, globalBase)
: url.startsWith('.')
? new URL(typeof window === 'undefined' ? 'http://n' : window.location.href)
? new URL(!process.env.browser ? 'http://n' : window.location.href)
: globalBase

const { pathname, searchParams, search, hash, href, origin } = new URL(
Expand Down
13 changes: 12 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.