Skip to content

How to integrate sonar for a Node JS project?

Last updated on November 21, 2022

In this post, I will show you SonarQube integration steps for Node-based projects.

SonarQube is an Open Source Software for static code scanning to discover potential vulnerabilities, bugs, and code smell.

We gonna use Docker to run the SonarQube server on the Docker engine so please install it and have Docker up and running on your machine.

Assuming that Docker is up and running on your machine, now to spin up the SonarQube server, we gonna run the below command from your terminal, it will pull the image from the Docker hub to the host machine and it will run the SonarQube server inside the Docker container at the given ports. Make sure that (9000 and 9002) ports are available, if not you can always use different ports.

docker run -d --name SonarQube -p 9000:9000 -p 9092:9092 sonarqube

To verify if the container started without errors, run the commands:

# List running docker containers
$ docker ps
# List all docker containers including the stopped one
$ docker ps -a

Now you can access the admin UI via http://localhost:9000

SONARQUBE SCANNER

Now that we have SonarQube set up, let’s install and set up the SonarQube Scanner to run against the codebase. We gonna use the npm module called sonarqube-scanner, so let’s install it with the below npm command.

npm install sonarqube-scanner --save-dev

Create a sonar-project.js file in the root of your project with the following code:


const sonarqubeScanner = require('sonarqube-scanner');
     sonarqubeScanner({
       serverUrl: 'http://localhost:9000',
       options : {
       'sonar.sources': '.',
       'sonar.inclusions' : 'src/**' // Entry point of your code
       }
     }, () => {});

By default, when scanning a project that has an npm package.json file, the reporting tool will use the package name and version that it finds in the JSON file.

In your package.json file, you can update the script section to add the command to execute:


"scripts": {
      …
      "sonar": "node sonar-project.js"
},

You can now run the scanner:

npm run sonar

The scan will take a few minutes the first time to complete, At the end of the run, you will be prompted with the URL to the project’s results

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments