Pirsch Docs>API and SDKs>JavaScript SDK

JavaScript SDK

21. Mar, 2021

The JavaScript SDK can be found on GitHub.

Installation

1
npm i pirsch-sdk

Create a Client

To use the API, you need to create a client on the settings page first and use the client ID, the secret, and hostname to set up the SDK.

1
2
3
4
5
6
7
8
var { Client } = require("pirsch-sdk");

var client = new Client({
    hostname: "example.com",
    clientID: "<client_id>",
    clientSecret: "<client_secret>",
    protocol: "https" // used to parse the request URL, default is http
});

From here on we can make API calls through the client. It will automatically update the access token using the credentials you provided.

Send a Page Hit

To monitor your website traffic, you need to send hits to Pirsch. This is done by calling the hit method from a handler function.

1
2
3
4
5
http.createServer((req, res) => {
    client.hit(client.hitFromRequest(req)).catch(e => {
        console.log(e);
    });
}).listen(8080);

hit takes a Hit object as an input and sends all relevant data to Pirsch. hitFromRequest is a helper method that returns a hit object for the given NodeJS http request. Depending on your framework, you might need to fill the object yourself.

Note that the handler above accepts all requests made by a client and will therefore lead to a lot of different paths being tracked. Usually you would make sure that only the page itself gets monitored by checking the requested path.

1
2
3
4
5
6
// parse the request URL to extract the pathname
const url = new URL(req.url || "", "https://example.com");

if(url.pathname === "/") {
    // send hit
}

You can send a hit whenever you want. If you have a page with dynamic content for example, you can check if the content was found and send a hit in that case, or otherwise ignore it.