Maximizing Code Quality: Unleashing the Power of Sonar in React App Continuous Development

Step by Step on using sonar tools for React development using Github Actions CI/CD

Muhammad Haddad
8 min readMay 24, 2023

Introduction

In today’s fast-paced software development landscape, maintaining high-quality code is crucial for the success of any project. Adhering to standard best practices ensures code readability, maintainability, and overall software quality. However, identifying and addressing code quality issues manually can be time-consuming and error-prone. This is where tools like SonarCloud come into play, providing automated code analysis and static code reviews to help developers identify and resolve potential issues early on. In this article, we will explore the importance of awareness to standard best practices supported by tools like SonarQube in the context of developing a React app, along with the benefits it brings to your workflow.

While React is a powerful JavaScript library for building user interfaces, it presents certain challenges when it comes to code quality. Some common issues include complex component hierarchies, JSX code complexity, and potential performance bottlenecks. SonarQube, with its React-specific rules and analysis capabilities, can help address these challenges. It provides insights into optimizing component structures, identifying potential performance bottlenecks, and enforcing best practices specific to React development. By leveraging SonarQube’s React-specific analysis, developers can ensure that their React applications are not only well-structured and maintainable but also performant and efficient.

Setting up SonarQube for React

SonarQube is a code analysis platform that integrates with your development workflow to provide continuous code quality monitoring. It offers a wide range of static code analysis rules, covering various programming languages, including JavaScript and TypeScript used in React app development. SonarQube analyzes your code for potential bugs, security vulnerabilities, code smells, and adherence to best practices. It helps you catch issues early, reducing the likelihood of introducing bugs into your application. Let’s get into the code !

Prepare your SonarCloud

create a new project on SonarQube to import your react app and fill all the form until you get to this page where you get a script to analyze the code on your project

prepare the sonar project

Setting up React

Now that you have the variable create a sonar-project.properties on the root folder

# this is sonar-project.properties
sonar.projectKey=ppl-vessel-maintenance-web
sonar.sources=src
sonar.exclusions= **/*.test.jsx,**/*.css, src/reportWebVitals.js, src/index.js
sonar.javascript.lcov.reportPaths=coverage/lcov.info
  1. sonar.projectKey=ppl-vessel-maintenance-web: Specifies the unique identifier for the SonarQube project. This key is used to differentiate this project from others in SonarQube.
  2. sonar.sources=src: Informs SonarQube about the source code directory to be analyzed. In this case, the "src" directory contains the JavaScript source files of the project.
  3. sonar.exclusions=**/*.test.jsx,**/*.css, src/reportWebVitals.js, src/index.js: Specifies the files or patterns that should be excluded from the analysis. The patterns given here indicate that any file with a ".test.jsx" extension, any file with a ".css" extension, "src/reportWebVitals.js", and "src/index.js" should be excluded from analysis. Excluding test files, CSS files, and specific entry point files like "index.js" and "reportWebVitals.js" from analysis can help reduce noise in the analysis results and focus on the main codebase
  4. sonar.javascript.lcov.reportPaths=coverage/lcov.info: Specifies the path to the coverage report file generated by a test coverage tool like Istanbul. In this case, the coverage report is located at "coverage/lcov.info". SonarQube can utilize this coverage report to provide insights into code coverage and identify areas of the code that lack proper testing.

Next, let’s edit the test script on our package.json so the React will have a coverage folder to be reported on sonarqube:

  "scripts": {
...
...
"test": "react-scripts test --coverage",
...
...
}

add the coverage folder to .gitignore so it won’t be pushed to the repo

# package directories .gitignore
..
node_modules
jspm_packages
coverage
..
..

To this point, we have our react app ready, let’s check the test script is work properly before we move on the next configuration. Run npm test on the terminal and see that the project produce a new folder named coverage.we are good to go if it is exist.

Configure CI/CD using Github Actions

On the earlier sonar configuration, we have the sonar’s variable to run the analysis, lets put it on our github action workflow. First let prepare the variable on the github secret, create two new repository secrets for your host url and the token

repository secrets for workflow

Next, configure the workflow on the react project, create a file called ci_cd.yml on .github/workflow

inside the yml file, configure the job:

  sonarscan:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: run test and coverage
run: |
npm install
npm test
- name: SonarQube Scan
uses: sonarsource/sonarqube-scan-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

This code represents a GitHub Actions workflow that includes a SonarQube scan for a project. Let’s go through each section and understand what it does:

needs: build
runs-on: ubuntu-latest
  • needs: build: Specifies that this workflow depends on another job named "build". This means that the "build" job must complete successfully before this workflow can start.
  • runs-on: ubuntu-latest: Specifies that the workflow will run on a machine with the latest version of the Ubuntu operating system.
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
  • actions/checkout@v3: This step uses the official GitHub Actions checkout action to fetch the source code of the project onto the runner machine. The @v3 indicates the specific version of the action being used.
  • with: fetch-depth: 0: Sets the fetch-depth option to 0, which means it fetches the entire commit history of the repository. This is necessary for SonarQube to analyze the full history of the code.
- name: run test and coverage
run: |
npm install
npm test
  • This step installs project dependencies using npm install and runs tests using npm test. It assumes the project is using npm as the package manager. Adjustments may be needed if using a different package manager.
- name: SonarQube Scan
uses: sonarsource/sonarqube-scan-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
  • This step performs the SonarQube scan using the sonarsource/sonarqube-scan-action GitHub Action. The uses key specifies the action and the @master indicates the specific version being used.
  • The env section sets the required environment variables for the SonarQube scan. The SONAR_TOKEN and SONAR_HOST_URL are set using GitHub secrets. You need to configure these secrets in the repository settings to securely provide the SonarQube authentication token and host URL.

Now we have configure all the things, let’s push the code and analyze it!

Understanding SonarQube Analysis Report

After we push the code to the repository, this is what the workflow should like

Sonarscan job on the github actions

After all the job completed, we can see the report on the sonar

sonarQube report

This report from SonarQube provides an overview of the code quality and analysis results for the project. Let’s break down each section of the report:

QUALITY GATE STATUS

  • Passed: Indicates that all conditions set in the quality gate have passed. The quality gate defines the criteria for acceptable code quality, including metrics like code bugs, vulnerabilities, code smells, coverage, and more.

MEASURES

  • New Code Since April 6, 2023: Specifies the timeframe for which new code metrics are shown. In this case, it shows the metrics for the code written in the past 2 months.
  • Overall Code: Total number of code issues found in the project.
  • Bugs (Reliability): Number of identified bugs in the code. Bugs represent code that may lead to unexpected behavior or errors.
  • Vulnerabilities (Security): Number of security vulnerabilities detected in the code. Vulnerabilities represent potential weaknesses that can be exploited by attackers.
  • Security Hotspots (Reviewed): Number of security hotspots identified in the code. Security hotspots are areas of the code that require review and potentially contain security vulnerabilities.
  • Debt: Technical debt, measured in minutes, represents the estimated time required to fix all code issues. Lower debt indicates better code quality.
  • Code Smells (Maintainability): Code smells are indicators of poor code structure or design that can negatively impact maintainability. This metric represents the number of code smells found in the project.
  • Coverage on 134 Lines to cover: Code coverage represents the percentage of code lines covered by automated tests. This metric shows the coverage on a specific number of lines that need to be covered.
  • Unit Tests: Percentage of code covered by unit tests. In this case, it shows 0.0%, indicating no unit test coverage.
  • Duplications on 468 Lines: This metric represents the number of lines of code that are duplicated within the project.
  • Duplicated Blocks: Number of duplicated code blocks found in the project.

ACTIVITY

  • Issues: Displays the number of issues found in the project, categorized by bugs, code smells, and vulnerabilities.
  • New Code: Graph showing the number of issues introduced in the code over time.
  • Activity: Provides a timeline of the project’s activity, including the date and time of quality gate status changes (passed or failed).

The report shows that the quality gate has passed in some instances and failed in others. It also provides metrics on bugs, vulnerabilities, code smells, coverage, and activity over time. This information helps developers and teams understand the current state of code quality and track progress in improving it over time.

Conclusion

Conclusion: Implementing SonarQube in your React app development workflow, along with GitHub Actions CI/CD, can significantly enhance code quality and maintainability. By leveraging SonarQube’s powerful code analysis capabilities, you can identify and address bugs, vulnerabilities, code smells, and performance issues early in the development process. This integration helps enforce coding best practices, optimize React-specific code structures, and improve overall code quality.

The step-by-step process outlined in this article has demonstrated how to set up SonarQube for React development, configure the necessary properties, and integrate it into GitHub Actions CI/CD. By following these steps, you can automate code analysis, run tests, and generate comprehensive reports, allowing you to continuously monitor code quality and make informed decisions for improvements.

The SonarQube analysis report provides valuable insights into various aspects of code quality, such as bugs, vulnerabilities, code smells, and test coverage. It enables developers to prioritize and address issues effectively, ensuring that the React app is reliable, secure, and maintainable.

In summary, by leveraging the power of SonarQube in your React app development workflow, you can maximize code quality, improve development efficiency, and deliver high-performing applications. Embracing standard best practices supported by tools like SonarQube empowers developers to build robust and maintainable React applications that meet the highest standards of quality and security.

--

--

Muhammad Haddad

Computer Science final year student at Univertas Indonesia. Exploring Backend, Automation, and Infrastructure. Github: @haddad9