How to Avoid Sitecore XM Cloud Next.js Build Errors: A Comprehensive Guide

How to Avoid Sitecore XM Cloud Next.js Build Errors: A Comprehensive Guide

10 min read

馃Introduction

When working with Sitecore XM Cloud and NextJS, developers often encounter build errors due to messages like "Field declared but never used" and "Property 'value' does not exist on type." These errors can be a barrier to development. However, there are effective ways to eliminate these errors. We will also cover how to prevent them, the essential role of Prettier and ESLint, and tips for identifying unused fields and properties. Additionally, we'll discuss the importance of using Prettier and ESLint for code quality checks before committing code to the repository and running npm run build locally.

鈿狅笍Common Build Errors in Next.js

  1. Field Declared but Never Used: This error typically arises when a variable or field is defined in the code but not utilized anywhere. It can lead to unnecessary clutter and confusion in your codebase.

    • Identify Unused Fields: Use your IDE's search functionality to locate where the field is declared. Generally Visual Studio Code IDE highlight unused variable like this 馃敐

      Error Details:

    • Remove or Utilize: Either remove the unused field or ensure it is used appropriately in your code.

      Error Details:

        Failed to compile.
        ./src/Layout.tsx
        20:11  Error: 'RouteFields' is defined but never used.  @typescript-eslint/no-unused-vars
        35:5  Error: Delete `路路`  prettier/prettier
        48:14  Error: Replace `路name="application-details"路content={layoutData?.sitecore?.context?.site?.name}路` with `鈵嶁弾路路路路路路路路路路name="application-details"鈵嶁弾路路路路路路路路路路content={layoutData?.sitecore?.context?.site?.name}`  prettier/prettier
        49:1  Error: Replace `路路路路路路路路data-siteName={layoutData?.sitecore?.context?.site?.name}路` with `路路路路路路路路路路data-siteName={layoutData?.sitecore?.context?.site?.name}`  prettier/prettier
        50:1  Error: Insert `路路`  prettier/prettier
      
  2. Property 'value' Does Not Exist on Type: This error occurs when TypeScript cannot find a property on a specified type, often due to incorrect type definitions or uninitialized variables. 馃敐

    • Check Type Definitions: Ensure that the type definitions for your objects are correct.

    • Update Types: Modify the type definitions to include the missing property or adjust your code to match the existing types.

      Error Details:

        Failed to compile.
        ./src/Layout.tsx:36:32
        Type error: Property 'value' does not exist on type 'Field<GenericFieldValue> | Item | Item[]'.
          Property 'value' does not exist on type 'Item'.
          34 |       <Scripts />
          35 |       <Head>
        > 36 |         <title>{fields?.Title?.value?.toString() || 'Page'}</title>
             |                                ^
      

      Solution:

      The error you're seeing means that the fields object might have items of different types, and not all of them have a value property. To fix this, you can add type checks to make sure you are accessing the value property only on the right types. 馃敐

          const getFieldValue = (field: any) => {
            return field?.value?.toString() || '';
          };
      

      In this updated code, I added a helper function getFieldValue to safely access the value property. This function checks if the field has a value property and returns it as a string, or returns an empty string if it doesn't exist. This should fix the TypeScript error you're facing.

馃憤Best Practices to Avoid Build Errors

Using Prettier and ESLint

Integrating Prettier and ESLint into your Next.js project is important for keeping your code clean and consistent. Here's how to set them up:

  1. Install ESLint and Prettier:bashCopy

     1npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier
    
  2. Configure ESLint: Create or update your .eslintrc.js file: 馃敐

     // File path: https://github.com/AmitKumar-AK/Sitecore.Demo.XMCloud.Verticals/blob/cdf80762aba717300ce13f350459c370819beb56/src/sxastarter/.eslintrc
     {
       "root": true,
       "extends": [
         "next",
         "next/core-web-vitals",
         "plugin:@typescript-eslint/recommended",
         "prettier",
         "plugin:yaml/recommended",
         "plugin:prettier/recommended"
       ],
       "plugins": ["@typescript-eslint", "prettier", "yaml", "react"],
       "ignorePatterns": [".generated/**/*", "**/*.d.ts", "**/*.js"],
       "rules": {
         "@next/next/no-img-element": "off", // Don't force next/image
         "jsx-a11y/alt-text": ["warn", { "elements": ["img"] }], // Don't force alt for <Image/> (sourced from Sitecore media)
         "no-unused-vars": "off",
         "@typescript-eslint/no-unused-vars": "error",
         "@typescript-eslint/no-explicit-any": "error",
         "jsx-quotes": ["error", "prefer-double"]
       }
     }
    
  3. Add Scripts to package.json:

     "scripts": {
         "eslint": "eslint ./src/**/*.tsx ./src/**/*.ts ./scripts/**/*.ts",
         "lint": "npm-run-all --serial eslint stylelint",
       }
    

Checking for Unused Fields and Properties

To identify unused fields and properties in your Next.js application, you can use the following tools and commands:

  1. Using ESLint: ESLint can be configured to warn about unused variables. Ensure you have the no-unused-vars rule enabled in your ESLint configuration (.eslintrc.js). 馃敐

  2. TypeScript Type Checking:

    The TypeScript compiler can help detect unused variables and properties. Run the following command:

     npx tsc --noEmit --skipLibCheck
    
  3. Validate Type Definitions:

    Running npx tsc helps find TypeScript compilation errors, including type errors like "Property 'value' does not exist on specific type." Here's how it can help:

    1. Type Checking: When you run npx tsc, the TypeScript compiler checks your code against the type definitions. If there's a type error, like trying to use a property that doesn't exist on a certain type, the compiler will let you know.

    2. Compile-Time Errors: TypeScript's static type checking finds errors before you run your code. This helps you spot and fix problems early in development.

    npx tsc

If you encounter type errors, check your interfaces and types to make sure they match the data structure you are using. 馃敐

  1. Typescript Prune:

    ts-prune is a tool used to identify and report unused exports in TypeScript projects. It helps developers clean up their codebase by finding and removing code that is no longer used, which can improve maintainability and reduce bundle size.

     npm install ts-prune --save-dev
     npx ts-prune --error
    

    I ran the above steps on the Sitecore.Demo.XMCloud.Verticals codebase and found the following results:

     \scripts\utils.ts:7 - watchItems
     \scripts\utils.ts:22 - getItems (used in module)
     \src\middleware.ts:5 - default
     \src\middleware.ts:9 - config
     .
     .
    

Running the Build Locally

Always run npm run build locally before pushing your code to the repository to ensure that your code compiles successfully and to catch errors early in the development process.

  1. Execute npm run build in your project directory

  2. Address any errors or warnings that appear

  3. Implement this step in your pre-commit hooks for consistency: this action prevents bad commits by running scripts before pushing code. The Sitecore.Demo.XMCloud.Verticals codebase already has this capability integrated: 馃敐

    Implementation:-

    The install-pre-push-hook.ts file is a script that sets up a Git pre-push hook. A pre-push hook is a script that runs automatically before you push changes to a remote repository. This script sets up a pre-push hook to run a lint check, making sure the code meets quality standards before you push changes.

     // File path: https://github.com/AmitKumar-AK/Sitecore.Demo.XMCloud.Verticals/blob/cdf80762aba717300ce13f350459c370819beb56/src/sxastarter/scripts/install-pre-push-hook.ts
     import fs from 'fs';
     import path from 'path';
     import { promisify } from 'util';
     import { exec } from 'child_process';
     import chalk from 'chalk';
    
     const installHooks = async () => {
       try {
         const appPath = path.join(__dirname, '..').replace(/\\/g, '/');
         const { stdout } = await promisify(exec)('git rev-parse --show-toplevel');
         const gitRootPath = stdout.trim();
         console.log(chalk.green(`Writing data to local .git folder ${gitRootPath}...`));
    
         const data = `#!/bin/sh
     #
     # pre-push hook runs our linter before we push our changes
     #
     # To skip this hook, use the --no-verify flag
     # when pushing.
     #
     echo "Running lint check..."
     cd ${appPath}
     npm run lint`;
    
         await promisify(fs.writeFile)(`${gitRootPath}/.git/hooks/pre-push`, data, 'utf8');
         console.log(chalk.green('Success'));
       } catch (error) {
         console.log(chalk.red(`Error installing hook: ${error}`));
       }
     };
    
     installHooks();
    

    Integration:-

    The "install-pre-push-hook" in your package.json file is probably a script that runs the install-pre-push-hook.ts script. This script sets up a Git pre-push hook to run lint checks before you push changes to the remote repository. 馃敐

     // File path: https://github.com/AmitKumar-AK/Sitecore.Demo.XMCloud.Verticals/blob/cdf80762aba717300ce13f350459c370819beb56/src/sxastarter/package.json#L108
     {
       "scripts": {
         "install-pre-push-hook": "ts-node --project tsconfig.scripts.json ./scripts/install-pre-push-hook.ts",
       }
     }
    
馃檹
Thank you to the Sitecore XM Cloud Team for providing these valuable integrations, which help build projects that meet industry standards.

鈿欙笍Tools and Commands Summary

Too/CommandPurpose
npm run lintRuns ESLint to check for code quality issues.
npm run formatFormats code using Prettier.
npx tsc --noEmitTypeScript type-checking without emitting output files.
npx ts-pruneFinds unused exports in TypeScript code.
npm run buildTo ensure that your code compiles successfully and to catch errors early in the development process.
npx prettier . --checkThe command npx prettier . --check checks if your project's files follow Prettier's formatting rules without modifying them, reporting any formatting issues found.
npm prettier --write .The command npm prettier --write . formats all files in the current directory and its subdirectories according to Prettier's rules by modifying them to match the formatting standards.

馃敠Conclusion

By following these strategies, you can effectively avoid common build errors in Sitecore XM Cloud with Next.js. Using tools like Prettier and ESLint not only improves code quality but also helps identify unused fields and properties. Regularly running build commands ensures that your application stays error-free and ready for deployment.

I wrote this article to share my experiences and solutions after encountering build errors in the DevOps pipeline when updating and committing code to the Git repository. These errors can be frustrating and time-consuming, but by following the checks and best practices in this guide, you can save a lot of time and effort. My goal is to help you avoid similar issues and achieve smoother builds in your Sitecore XM Cloud projects with Next.js. By using these strategies, you can enhance your development process and achieve better, more reliable results.

If you'd like to share your experience with handling these errors, feel free to comment below! 馃

馃檹Credit/References

馃彄Pingback

Type error: 'PageComponent' is declared but never usedGraphql query error ! variable is declared but never usedSitecore Next.js Sitecore Forms Validation
Simplify Sitecore XM Cloud Projects with GitHub Codespaceswarning: it is defined but never usedUnderstanding TypeScript Error: Property 'value' does not exist on type 'never' 馃敐
Multilingual sites in Sitecore Headless with Next.js + GraphQLNEXT-1090 Property 'set' does not exist on type 'ReadonlyRequestCookies'Why this next.js and typescript page says "Property 'data' does not exist on type"
"Mastering Sitecore XM Cloud: Avoiding Common Next.js Build Errors" - Discover essential tips to prevent build errors in Sitecore XM Cloud with Next.js. Read more"Comprehensive Guide to Preventing Next.js Build Errors in Sitecore XM Cloud" - Learn how to troubleshoot and avoid build errors in Sitecore XM Cloud. Read more"Avoiding Build Errors in Sitecore XM Cloud with Next.js: Best Practices" - Implement best practices to ensure smooth builds in Sitecore XM Cloud. Read more
"Next.js Build Error Solutions for Sitecore XM Cloud" - Effective solutions to common build errors in Sitecore XM Cloud with Next.js. Read more"Step-by-Step Guide to Avoiding Next.js Build Errors in Sitecore XM Cloud" - Follow these steps to prevent build errors in Sitecore XM Cloud. Read more"Troubleshooting Next.js Build Errors in Sitecore XM Cloud" - A troubleshooting guide for resolving build errors in Sitecore XM Cloud. Read more
"Preventing Build Errors in Sitecore XM Cloud: Next.js Edition" - Tips and tricks to avoid build errors in Sitecore XM Cloud with Next.js. Read more"How to Ensure Error-Free Builds in Sitecore XM Cloud with Next.js" - Strategies to ensure smooth and error-free builds in Sitecore XM Cloud. Read more"Avoiding Common Pitfalls: Next.js Build Errors in Sitecore XM Cloud" - Learn how to avoid common pitfalls that lead to build errors in Sitecore XM Cloud. Read more
"Sitecore XM Cloud and Next.js: A Guide to Error-Free Builds" - Comprehensive guide to achieving error-free builds in Sitecore XM Cloud with Next.js. Read more"Enhancing Sitecore Search Results: Highlighting Searched Terms" - Techniques to highlight searched terms in Sitecore Search results. Read more"Exploring Search Options in Sitecore XM Cloud" - A comprehensive guide to search options in Sitecore XM Cloud. Read more
"Boost Your Search Results: Mastering Sitecore Search Optimization" - Tips and tricks for optimizing search results in Sitecore. Read more"Sitecore Experience Manager Cloud (XM Cloud) Building Blocks" - Discover the fundamental components of Sitecore XM Cloud. Read more"Configure RSS Feed Trigger in Sitecore Search" - Learn how to set up RSS feed triggers in Sitecore Search. Read more
"How to Deploy Sitecore XM Cloud Foundation Head to Vercel in Simple Steps" - Step-by-step guide to deploying Sitecore XM Cloud Foundation Head to Vercel. Read more"What is Sitecore Stream?" - Understand the features and benefits of Sitecore Stream. Read more"Quick Fixes for Docker's Manifest Not Found Error" - Discover quick solutions for Docker's manifest not found error. Read more 馃敐