Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Next
Enforce font-display behavior with Google Fonts.
import React from 'react';
const BadFont = () => (
<link
href="https://fonts.googleapis.com/css?family=Roboto"
rel="stylesheet"
/>
);
export default BadFont;
-
This ESLint rule specifically targets the use of Google Fonts by checking if the
<link>
element’shref
attribute’s value begins with the official Google Fonts API URL. This ensures that only Google Fonts links are examined for thefont-display
feature, making the rule highly targeted and relevant when optimizing font loading strategies for web performance. -
By enforcing a
font-display
parameter in Google Fonts links, the rule encourages developers to explicitly define how fonts should be loaded. This can improve the user experience by potentially reducing invisible text during web page loading, as developers can select afont-display
strategy (e.g.,swap
,fallback
,optional
) that best suits their application’s needs. -
The rule further guides best practices by recommending against certain
font-display
values likeauto
,block
, andfallback
. This advice steers developers away from choices that might lead to poorer performance or user experience. For example,block
can cause a significant delay in text rendering until the font has fully loaded, which might not be ideal for users on slow connections. -
By providing specific feedback on the recommended inclusion of
&display=optional
or highlighting the non-recommended usage of certain display values, this ESLint rule also serves an educational purpose. It alerts developers to the importance of font rendering strategies and their impact on web performance and user experience, potentially leading to better-informed decisions in web development projects.
Ensure preconnect
is used with Google Fonts.
function MyComponent() {
return (
<head>
<link href="https://fonts.gstatic.com" />
</head>
);
}
-
This ESLint rule focuses on optimizing the loading performance of Google Fonts by ensuring that the
preconnect
link relation is used. The preconnect mechanism allows the browser to set up early connections before an HTTP request is actually sent to the server. This can include DNS lookups, TLS negotiations, and TCP handshakes. By implementing preconnect specifically for Google Fonts, web developers can decrease the time it takes to fetch the fonts, resulting in faster page load times. -
The rule is designed to detect missing
preconnect
links for Google Fonts loaded through the<link>
tag in JSX files, which are commonly used in React-based projects, including Next.js applications. Without this rule, developers might overlook the inclusion of preconnect, potentially degrading the site’s performance, especially on first load where the font files are required to render text styled with those fonts. -
By automatically flagging instances where the
rel="preconnect"
attribute is missing on<link>
tags that includehref="https://fonts.gstatic.com"
, this rule helps maintain a high standard of code quality and adherence to best practices for web performance. As a consequence, it serves not just to correct an oversight but also to educate developers about the importance of preconnection when dealing with external resources like fonts. -
The rule also improves the overall user experience of web applications. Faster font loading can significantly impact visual stability and cumulative layout shift scores, which are critical metrics for user experience and SEO. By ensuring that Google Fonts are preconnected, this rule helps prevent scenarios where text becomes visible with a fallback font and then shifts when the custom font loads, thus enhancing the consistency and professionalism of the web presence.
Enforce id
attribute on next/script
components with inline content.
import Script from 'next/script';
function Example() {
return (
<Script>
{`console.log('Hello, world!');`}
</Script>
);
}
-
This rule ensures that
next/script
components with inline JavaScript are easily identifiable by enforcing the presence of anid
attribute. This makes it simpler to reference and potentially manipulate these scripts later in the codebase or through developer tools, enhancing maintainability and debuggability. -
By requiring an
id
on inline scripts, it aids in enforcing a standardized practice within a development team or project, leading to a more organized and readable codebase. This practice can be particularly beneficial in large projects where consistency in code structure is crucial for efficient collaboration and code review processes. -
The rule helps in avoiding potential conflicts or side effects by clearly identifying script elements that are dynamically added to the page. This is particularly relevant in the context of Next.js projects where server-side rendering and client-side hydration might cause scripts to execute in an unexpected order or multiple times if not properly managed.
-
It indirectly encourages developers to think more carefully about the scripts they inline within their components, promoting the use of external script files where appropriate. This can lead to better performance and caching strategies, as well as cleaner code by separate concerns (markup vs. behavior).
Prefer next/script
component when using the inline script for Google Analytics.
export default function Home() {
return (
<>
<script
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');
`,
}}
/>
</>
);
}
-
This ESLint rule ensures that developers use the
next/script
component for adding Google Analytics (GA) scripts to Next.js applications, which is specifically optimized for Next.js’ performance characteristics, leading to better loading times and potentially improved site performance metrics. -
By encouraging the use of
next/script
with a specific loading strategy (e.g., ‘lazyOnload’), the rule helps ensure that the GA script does not impact the critical rendering path or delay the interactive readiness of the page, thus maintaining a smooth user experience. -
This rule aids in standardizing the way GA scripts are included in Next.js projects, making the codebase more consistent and easier for teams to maintain and for new developers to understand how analytics should be integrated within the framework.
-
It also serves to mitigate potential security risks by discouraging the use of the
dangerouslySetInnerHTML
attribute for inserting GA tracking code directly into the HTML. This practice can be unsafe if not properly managed, as it opens the door to cross-site scripting (XSS) attacks if the content is not properly sanitized.
Prevent assignment to the module
variable.
function setup() {
let module = { exports: {} };
module.exports = {
hello: 'world',
};
console.log(module);
}
setup();
-
The rule prevents potential confusion and errors in Next.js applications by disallowing the assignment to a variable named
module
, a global object in Node.js environment. This ensures that developers do not unintentionally overwrite or misuse themodule
variable, which could lead to unforeseen bugs and behavior in the application, particularly in server-side code or when using Next.js’ API routes. -
This ESLint rule is specifically tailored to the unique environment of Next.js projects, which can encompass both client-side and server-side JavaScript. By enforcing a naming convention that avoids using the reserved
module
variable, it helps maintain a clearer boundary between Node.js modules and JavaScript variables that developers define, reducing the risk of name collisions and the ensuing runtime errors. -
The rule enforces better coding practices by encouraging developers to choose more descriptive and unique names for their variables instead of relying on generic terms like
module
. This not only avoids the specific technical issue of overwriting the globalmodule
variable but also enhances code readability and maintainability by making it clearer what each variable represents. -
Automatically flagging assignments to the
module
variable as errors, as this rule does, aids in code review processes and contributes to the overall quality assurance of the codebase. It acts as an automated guardrail that prompts developers to rethink and refactor their code in real-time, thereby preventing the deployment of potentially problematic code that could affect the module system or application stability.
Prevent client components from being async functions.
// "use client" indicates this is intended to be a client component
"use client";
export default async function MyComponent() {
const data = await fetchData();
return (
<div>
<h1>Async Client Component</h1>
<p>{data}</p>
</div>
);
}
- The rule prevents the use of async functions for client components in Next.js projects, ensuring that components follow the framework’s best practices for handling asynchronous operations, leading to better performance and consistency in the codebase.
- It enforces the pattern of using hooks like
useState
anduseEffect
for handling side effects and asynchronous data fetching in functional components, which is the recommended approach in React, thereby maintaining uniformity and improving readability across the project. - By disallowing async functions in client components, this rule helps avoid potential issues with render timing and state management, ensuring that components properly wait for necessary data before rendering, which can improve the user experience by preventing incomplete or incorrectly rendered components.
- The rule aids in identifying refactoring opportunities in the code where developers might inadvertently use async functions in client components, guiding them to adopt patterns that leverage React’s built-in hooks for asynchronous operations, aligning with modern React development practices and enhancing code maintainability.
Prevent usage of next/script
’s beforeInteractive
strategy outside of pages/_document.js
.
// In a file like pages/index.js or components/MyComponent.js
import Script from 'next/script';
function MyComponent() {
return (
<>
<Script
src="https://example.com/some-script.js"
strategy="beforeInteractive"
/>
<p>Hello, world!</p>
</>
);
}
export default MyComponent;
- Enforces best practices for script loading strategies specific to Next.js applications by ensuring the
beforeInteractive
strategy is used correctly, which helps maintain the application’s performance by loading scripts before the page becomes interactive, but only when it’s appropriate to do so. - Prevents the misuse of the
next/script
’sbeforeInteractive
strategy in components or pages other thanpages/_document.js
, which could lead to scripts being loaded too early in the app’s lifecycle on pages where it’s not required, potentially affecting page speed and user experience negatively. - Ensures consistency and the correct application of Next.js conventions regarding script loading, making the application easier to understand for new developers and helping maintain code quality across large projects.
- Helps identify and prevent potential errors in the application’s runtime behavior early in the development process by providing clear feedback if the
beforeInteractive
strategy is used outside its intended context, thus aiding in debugging and reducing time spent on finding performance-related issues.
Prevent manual stylesheet tags.
import React from 'react';
class MyComponent extends React.Component {
render() {
return (
<div>
<link rel="stylesheet" href="/static/styles.css" />
<h1>Hello, world!</h1>
</div>
);
}
}
- Encourages the use of Next.js built-in CSS and Sass support for including styles, which allows for features like hot reloading and potentially more efficient bundling compared to manual
<link>
tags in the JSX code. This leads to enhanced development experience and performance optimization. - Promotes consistency in the way stylesheets are included across Next.js projects, making codebases easier to understand and maintain. By enforcing a uniform approach, it minimizes the cognitive load for new developers or contributors to the project.
- Prevents potential security risks associated with the manual inclusion of stylesheets from external sources by encouraging developers to import stylesheets as modules. This also implicitly encourages reviewing the contents of CSS files before including them in the project.
- Helps in leveraging Next.js’s automatic CSS optimization features such as code splitting and dead code elimination. When CSS is imported directly into JavaScript modules, Next.js can more intelligently split and include only the necessary CSS, reducing the size of the final bundle delivered to clients.
Prevent importing next/document
outside of pages/_document.js
.
// Assuming this is in pages/about.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
- Ensures that
next/document
is only imported in the custom document file (_document.js
), which is the proper place for applying global CSS styles and setting up the HTML structure for Next.js applications. This helps maintain the intended functionality of_document.js
as a place for customization that applies to all pages. - Prevents potential misuse or confusion about where to import and use the
Document
component. SinceDocument
is intended to be used once and applied globally, importing it into individual pages could lead to misconceptions about its purpose and usage within the Next.js framework. - Enhances project maintainability by enforcing a consistent structure and import practice across the development team. By restricting the import of
next/document
to_document.js
, it simplifies understanding the flow and structure of Next.js projects, especially for new developers. - Prevents runtime errors and unexpected behavior in Next.js applications.
next/document
contains server-side rendering specific logic that should not be included in regular pages or components. Importing it outside of_document.js
could introduce server-rendering issues or negatively impact the performance and SEO of the application.
Prevent duplicate usage of <Head>
in pages/_document.js
.
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
{/* Metadata and links for the head of the document */}
</Head>
<body>
<Head>
{/* This is incorrectly duplicated. It should be merged with the first <Head> instance. */}
<link rel="stylesheet" href="/myStylesheet.css" />
</Head>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
- The rule specifically targets the prevention of duplicate
<Head>
components in_document.js
for Next.js applications, helping ensure that SEO and meta tags are efficiently centralized for easier management and maintenance. This centralization avoids conflicting metadata or redundant link tags that could negatively impact SEO or page performance. - It automatically enforces best practices in _document.js structure by encouraging developers to merge all their
<Head>
content into a single instance. This consolidation can lead to cleaner and more readable code, making it easier for developers to track where specific meta tags, stylesheets, or other head-related elements are declared. - By detecting and reporting multiple instances of
<Head>
components, the rule aids in debugging and code review processes. When developers inadvertently insert duplicate<Head>
tags, especially in large projects or when working in teams, this rule quickly highlights the issue, preventing potential head-related conflicts before they reach production. - The rule contributes to a uniform development standard within a team working on a Next.js project. By enforcing a single
<Head>
component through ESLint, it ensures that all developers adhere to this pattern, reducing the likelihood of inconsistencies in the project’s codebase and simplifying the code review process.
Prevent usage of <head>
element.
import React from 'react';
class MyPage extends React.Component {
render() {
return (
<html>
<head>
<title>My Page Title</title>
</head>
<body>
<div>Welcome to my page!</div>
</body>
</html>
);
}
}
export default MyPage;
-
This ESLint rule is designed to enforce the use of
<Head />
fromnext/head
instead of the native HTML<head>
element within Next.js applications. This is crucial because Next.js has specific enhancements and optimizations tied to its<Head />
component, which do not apply when using the traditional<head>
element. These enhancements can include automatically handling duplicates, ordering of script tags, and optimizing loading for performance. -
It specifically targets files within the pages directory by checking the path of the file being linted. This is important as using the native
<head>
element inside the pages directory can lead to unexpected behaviors in Next.js applications, such as issues with server-side rendering or meta tags not being correctly updated. By ensuring that developers use<Head />
fromnext/head
, we maintain consistency and leverage Next.js features optimally. -
The rule provides immediate feedback to developers by reporting an appropriate message when the
<head>
element is used. This educates developers on best practices within Next.js applications and guides them towards using<Head />
for modifying the document’s head, ensuring they are aware of the preferred method and its benefits, such as ease of setting per-page SEO attributes. -
By encouraging the use of
<Head />
fromnext/head
, this rule directly supports enhanced SEO capabilities and better performance. The<Head />
component ensures that meta tags are correctly merged or updated on page navigation, which is essential for single-page applications where page content changes without a full page reload. This aligns with modern web development practices, where SEO and performance are crucial for the visibility and user experience of web applications.
Prevent usage of next/head
in pages/_document.js
.
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'
import Head from 'next/head'; // This is incorrect in _document.js
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<title>My Page Title</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
- This rule specifically discourages the importation of
next/head
withinpages/_document.js
becausenext/head
is intended for repeating head elements across pages rather than for modifying the document’s head directly. This ensures that the head modifications are done correctly at the document level using<Head />
fromnext/document
, which is the proper way to include elements in the head for all pages. - By enforcing the use of
<Head />
fromnext/document
in_document.js
, it promotes consistency and the correct usage patterns within the Next.js framework. This reduces the risk of common mistakes by developers new to or unfamiliar with the intricacies of Next.js, enhancing the maintainability and readability of the code. - Preventing the incorrect import of
next/head
in_document.js
aids in avoiding conflicts or unexpected behavior that can arise from misusingnext/head
at the document level. Sincenext/head
is designed to be used within individual pages or components, its usage in_document.js
can lead to problems with server-side rendering or the overall page head elements rendering. - The rule helps in enforcing best practices and adhering to the architectural design of Next.js applications. By guiding developers to use the correct components in their appropriate contexts (
<Head />
fromnext/document
for modifying the document’s head), it ensures that the application leverages Next.js features optimally, leading to better performance and a more predictable application behavior.
Prevent usage of <a>
elements to navigate to internal Next.js pages.
// Bad Example: Using <a> tag for internal page navigation
function HomePage() {
return (
<div>
<h1>Welcome to Our Home Page</h1>
<a href="/about">Go to About Page</a>
</div>
);
}
- This rule ensures consistent use of the Next.js
<Link />
component for internal navigation, leveraging its prefetching capabilities for faster page transitions, unlike the traditional<a>
tag that does not prefetch pages. - By discouraging the use of
<a>
tags for internal links, it helps developers avoid the common pitfall of full page reloads on navigation within a Next.js app, which can degrade the app’s performance and user experience. - The rule includes logic to dynamically find pages and app directories within the project structure, making it adaptable to custom Next.js setups and ensuring accurate detection of internal links that should use
<Link />
. - It promotes best practices in Next.js development by automatically identifying improper usage patterns of
<a>
tags for internal navigation during code analysis, thereby helping maintain code quality and consistency across large codebases.
Prevent usage of <img>
element due to slower LCP and higher bandwidth.
import React from 'react';
function UserProfile({ src, alt }) {
return (
<div>
<h2>User Profile Picture</h2>
<img src={src} alt={alt} />
</div>
);
}
-
Ensures optimized image loading by encouraging the use of
<Image />
fromnext/image
instead of the standard<img>
tag, directly impacting the Largest Contentful Paint (LCP) metric favorably. LCP is crucial for user experience and SEO. -
Prevents higher bandwidth usage which can occur with unoptimized images loaded via the
<img>
tag. The<Image />
component from Next.js automatically optimizes images for different screen sizes and resolutions, reducing unnecessary data transfer. -
Encourages developer compliance with best practices around image optimization in Next.js applications. By flagging
<img>
elements, developers are nudged towards using features specific to Next.js that are designed to enhance performance and user experience. -
Allows for exceptions within the context of a
<picture>
element, acknowledging that there are valid use cases for<img>
in combination with<picture>
for manually specified image sources for different scenarios. This flexibility ensures that the rule doesn’t enforce a blanket restriction but rather guides towards optimization except when a specific use case justifies otherwise.
Prevent page-only custom fonts.
// pages/example.js
import Head from 'next/head';
export default function ExamplePage() {
return (
<>
<Head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" />
</Head>
<div>
<p style={{ fontFamily: 'Roboto' }}>This is text with the Roboto font applied.</p>
</div>
</>
);
}
-
Encourages best practices for font loading in Next.js projects by ensuring custom fonts are placed in
_document.js
for global availability, preventing the need to import them on a per-page basis which can lead to performance issues. -
Helps maintain a consistent user experience across the entire application by avoiding the scenario where custom fonts are only available on certain pages, hence ensuring design consistency.
-
Directly addresses performance optimization by leveraging Next.js’s automatic font optimization feature when fonts are correctly placed in the
_document.js
file, leading to faster page load times. -
Prevents potential layout shifts or FOIT (Flash of Invisible Text) by ensuring fonts are loaded before the page is rendered to the user, as opposed to being loaded at the page level where it might delay text rendering.
Prevent usage of next/script
in next/head
component.
import Head from 'next/head';
import Script from 'next/script';
function MyComponent() {
return (
<Head>
<title>My Page Title</title>
<Script src="https://example.com/myscript.js" strategy="lazyOnload" />
</Head>
);
}
- Ensures compliance with the Next.js best practices by preventing the
<Script>
component from being used inside the<Head>
component, which is a pattern discouraged by the Next.js framework itself. This helps maintain the structural integrity of your Next.js application. - Improves page loading performance by preventing scripts from being loaded in the
<head>
element. Inserting scripts directly into the<head>
can block page rendering until the script is downloaded and executed. By moving the<Script>
component outside of<Head>
, scripts can be managed more efficiently, especially when using loading strategies likelazyOnload
. - Enhances SEO by ensuring that scripts do not interfere with the critical rendering path of the page. Scripts inserted in the
<head>
can delay the rendering of the page content, which can negatively impact search engine rankings as search engines prioritize fast-loading pages. - Reduces the likelihood of JavaScript execution errors that might occur due to scripts being loaded before the Document Object Model (DOM) is fully constructed. By enforcing the separation of the
<Script>
component from the<Head>
, it encourages developers to organize their scripts in a way that respects the loading and execution order required for proper initialization of web pages.
Prevent usage of styled-jsx
in pages/_document.js
.
// Bad Code Example in pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<style jsx>{`
body {
background-color: #f0f0f0;
}
`}</style>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
- This ESLint rule helps enforce best practices by preventing the use of
styled-jsx
inpages/_document.js
, which is crucial because_document.js
is meant for augmenting the initial HTML document structure and not for defining page-level styles. This ensures that styles are defined where they are most efficient and maintainable. - By disallowing
styled-jsx
in_document.js
, the rule promotes the usage of global stylesheets or CSS-in-JS libraries in a way that aligns with Next.js’s recommended patterns for styling. This supports better performance and consistency in styling across the application. - The rule aids in identifying and reporting instances where
styled-jsx
is incorrectly used within_document.js
, providing immediate feedback to developers. This helps catch and correct potential misuse early in the development process, reducing the likelihood of styling issues in production. - It directly guides developers towards implementing styling in a manner that is optimized for server-side rendering (SSR) by Next.js. Since
_document.js
is mainly concerned with server-rendered document markup, incorporating styles outside of this file (as suggested in the fixed code example) aligns with Next.js’s architecture, ensuring styles are correctly applied and managed.
Prevent synchronous scripts.
import Head from 'next/head'
export default function Home() {
return (
<>
<Head>
<script src="/path/to/script.js"></script>
</Head>
</>
)
}
-
The rule specifically targets the inclusion of synchronous scripts in JSX elements, ensuring that scripts included in projects using the Next.js framework do not block the parsing of the HTML document. This is crucial for maintaining a fast and responsive web application, as synchronous scripts can significantly increase page load times.
-
By checking for the presence of
async
ordefer
attributes in script tags, this rule promotes the use of asynchronous or deferred scripts. These practices are essential for modern web development, as they allow scripts to be loaded in the background or after the HTML document has been fully parsed, thereby improving the site’s performance and user experience. -
Given that this rule reports the use of synchronous scripts, it serves as a direct reminder to developers to follow best practices for script loading. Synchronous scripts can lead to performance bottlenecks, especially in large applications built with Next.js, making this rule critical for ensuring that such issues are caught early during development.
-
The rule also enhances the overall maintainability and scalability of Next.js applications by enforcing a consistent code style regarding how scripts are included. This can lead to more readable and uniform codebases, making it easier for teams to collaborate and for individual developers to understand and edit the code long-term.
Prevent usage of <title>
with Head
component from next/document
.
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<title>My Page Title</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
- The rule specifically targets and prevents the misuse of the
<title>
element within the<Head>
component imported fromnext/document
, ensuring that developers follow the best practice of defining titles at the page level rather than in the document head. This approach aligns with Next.js’s recommended way to handle document metadata, ensuring consistent behavior across different pages in the application. - By enforcing the use of
<Head>
fromnext/head
for setting the page title, this rule helps maintain the dynamic nature of single-page applications (SPAs) built with Next.js. Titles can be updated based on the page content or user interactions, improving the user experience and making the application more accessible and SEO-friendly. - This rule aids in preventing a common mistake that could lead to harder-to-debug errors or unexpected behavior in a Next.js application. Since
<title>
tags in_document.js
will not update dynamically as the user navigates through the application, identifying the misuse of<Head>
fromnext/document
for titles ensures that developers are immediately made aware of the incorrect implementation before it becomes an issue. - It encourages a more modular and component-based approach to defining meta information, such as page titles, by restricting the use of
<title>
within the<Head>
component fromnext/document
. This modular approach is in line with modern web development practices, promoting code reuse and maintainability. Ensuring titles are set within specific pages rather than globally in_document.js
allows for more granular control over how pages are presented and indexed by search engines.
Prevent common typos in Next.js data fetching functions.
export async function getStaticsProps(context) {
// Fetch data for static rendering
const data = await fetchData();
return {
props: {
data,
},
};
}
- Reduces the risk of runtime errors related to incorrectly named Next.js data fetching methods, which may lead to unexpected behavior or broken builds due to typos such as
getStaticsProps
instead ofgetStaticProps
. - Enhances code readability and maintainability by ensuring data fetching functions are correctly named according to Next.js conventions, making it easier for team members to recognize and use these functions properly.
- Increases development efficiency by automatically detecting and suggesting the correct spelling of misnamed functions, thus saving developers time that would otherwise be spent debugging why their data fetching isn’t working as expected.
- Improves the overall reliability and stability of Next.js applications by ensuring that server-side and static generation features are correctly implemented, leveraging the full capabilities of the framework without hindered functionality due to simple naming mistakes.
Prevent duplicate polyfills from Polyfill.io.
import Script from 'next/script';
const MyComponent = () => (
<div>
<Script src="https://polyfill.io/v3/polyfill.min.js?features=default,fetch,Array.prototype.includes" />
<p>Hello, world!</p>
</div>
);
- This rule specifically targets and prevents the inclusion of polyfills that are already provided by Next.js, helping to avoid unnecessary code duplication. This is particularly useful because Next.js includes a number of polyfills by default, and explicitly adding those same polyfills via the Polyfill.io service can lead to wasteful loading of scripts that are already available, negatively impacting page load performance.
- The rule automates the identification of unwanted polyfills by intercepting import declarations and script elements that source from Polyfill.io, which can significantly streamline the development process. Developers don’t need to manually track and cross-reference the polyfills included by Next.js versus those requested from Polyfill.io, reducing the risk of inadvertently including duplicates.
- It encourages best practices in terms of optimizing web performance. By ensuring that only necessary polyfills are loaded, the rule indirectly contributes to faster load times and a better overall user experience. This is especially important for applications targeting a wide range of browsers, where conditional loading of polyfills can significantly affect performance.
- The rule provides clear feedback to developers when duplicate polyfills are detected, including details about which polyfills are unnecessary. This educational aspect can help developers learn more about the default features provided by Next.js and how to efficiently manage polyfill inclusion, making it an excellent tool for teams new to the framework or those looking to optimize their existing applications.