One place for hosting & domains

      October 2022

      Introduction to the Bun JavaScript Runtime


      Bun introduces a new JavaScript runtime with exceptional performance, built-in bundling & transpiling, and first-class support for TypeScript & JSX. This up-and-coming tool promises to be an asset for JavaScript developers and a strong competitor to Node.js and Deno.

      In this tutorial, learn about the Bun JavaScript runtime and how it compares to other runtimes like Node.js and Deno. See how to set up Bun on your own system, and follow along to build an example React application with it.

      Before You Begin

      1. Familiarize yourself with our
        Getting Started with Linode guide, and complete the steps for setting your Linode’s hostname and timezone.

      2. This guide uses sudo wherever possible. Complete the sections of our
        How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        • Debian and Ubuntu:

          sudo apt update && sudo apt upgrade
          
        • AlmaLinux, CentOS Stream (8 or later), Fedora, and Rocky Linux:

          sudo dnf upgrade
          

      Note

      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Users and Groups guide.

      What Is Bun?

      Bun enters the field of JavaScript runtimes opposite options like Node.js and Deno. Built on the lightning-fast JavaScriptCore engine, the Bun runtime stands out for its speed and built-in bundling & transpiling features.

      These next sections aim to make you more familiar with Bun and what it has to offer. Keep reading to learn more about JavaScript runtimes in general, and how Bun stacks up against its main competitors.

      What Are JavaScript Runtimes?

      JavaScript runtimes are tools that allow you to run JavaScript outside of a browser. With a JavaScript runtime, you can use JavaScript to build server, desktop, and mobile applications.

      By far, the predominant JavaScript runtime is Node.js. Built on the V8 JavaScript engine behind Google Chrome, Node.js is the default JavaScript runtime for many developers.

      Recently, the creator of Node.js put out a new JavaScript runtime, Deno. The Deno runtime, like Node.js, is built on the V8 JavaScript engine. However, Deno introduces numerous fundamental improvements to Node.js in terms of security, performance, and more. It also adds first-class support for TypeScript and JSX.

      The Bun Runtime

      The Bun runtime arose with a fresh approach to JavaScript runtimes. Developed using the Zig programming language, Bun constructs its runtime on the JavaScriptCore engine, used in Apple’s Safari web browser. The result is an incredibly fast runtime.

      Additionally, Bun has built-in handling for bundling and transpiling. With other runtimes, you need to rely on outside tools for bundling your JavaScript projects and for transpiling code from another language. Bun handles all of these features.

      What’s more, Bun’s runtime implements the Node.js algorithm for resolving modules. This means that Bun can make use of NPM packages. Bun’s bundler can find and install packages from the vast NPM repository and manage their dependencies, giving you a full-featured and seamless bundler.

      Like Deno, Bun also comes with first-class support for the TypeScript and JSX languages.

      Bun vs Node.js and Deno

      Bun offers some of the same advantages over Node.js as Deno. Besides the aforementioned first-class support for TypeScript and JSX, both offer performance and quality-of-life improvements over Node.js.

      However, the Bun runtime also aims to exceed Deno in terms of performance. Bun’s use of the JavaScriptCore engine has allowed Bun to achieve immense speed gains in its execution of JavaScript programs.

      With Bun, you also get simplified tooling. Bun includes transpiling and bundling features, which keeps you from having to adopt and maintain separate tools for those tasks.

      How to Install Bun

      Before proceeding, make sure your Linux system uses a version supported by Bun. Currently, Bun runs on systems using at least version 5.1 of the Linux kernel (though it prefers 5.6).

      You can check your kernel version with the command:

      uname -r
      

      On a CentOS Stream 9 system, for instance, you could expect an output like the following:

      5.14.0-80.el9.x86_64

      For reference, here are versions of some popular Linux distributions that use at least version 5.1 of the Linux kernel:

      • CentOS Stream (9 or newer)
      • Debian (11 or newer)
      • Fedora (34 or newer)
      • Ubuntu (20.04 LTS or newer)

      The Bun installation script requires that you have Unzip installed on your system. You can install Unzip using one of the following commands:

      • Debian and Ubuntu:

        sudo apt install unzip
        
      • AlmaLinux, CentOS Stream, Fedora, and Rocky Linux:

        sudo dnf install unzip
        

      Bun can be installed using an installation script. The command below accesses the script and runs it in your shell session:

      curl https://bun.sh/install | bash
      

      Once finished, the Bun installation script displays a success message:

      bun was installed successfully to /home/example-user/.bun/bin/bun
      [...]

      The script may also inform you to add two lines to your .bashrc file. You can quickly do so using the following commands:

      echo 'export BUN_INSTALL="/home/example-user/.bun"' >> ~/.bashrc
      echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> ~/.bashrc
      

      Restart your shell session by exiting and reentering it, and you are finally ready to start using Bun. At this point you can verify your installation by checking the Bun version:

      bun -v
      
      0.1.5

      Example of a Bun Project

      Like NPM, Bun can be used to create and manage application projects. To give you an idea of Bun’s capabilities, the next series of steps walk you through creating and running a React application with Bun.

      The example adds a simple analog clock widget to the base React template, which lets you see more of how Bun manages project dependencies.

      1. Create a new Bun project. This is done by giving the bun create command with a template name and project folder.

        You can get a list of some useful available templates by running the create command without any arguments:

        bun create
        

        For this example, create your project from the React template, and give the project a directory of example-react-app, like this:

        bun create react ./example-react-app
        
      2. Afterward, be sure to change into the new project directory. The rest of these steps assume you are working out of this directory:

        cd example-react-app
        
      3. This already gives you a working React application, you just need to start it:

        bun dev
        
      4. You can see the application in action by navigating to localhost:3000 in your browser.

        To see the application remotely, you can use an SSH tunnel.

        • On Windows, use the PuTTY tool to set up your SSH tunnel. Follow the appropriate section of the
          Setting up an SSH Tunnel with Your Linode for Safe Browsing guide, replacing the example port number there with 3000.

        • On macOS or Linux, use the following command to set up the SSH tunnel. Replace example-user with your username on the application server and 192.0.2.0 with the server’s IP address:

          ssh -L3000:localhost:3000 example-user@192.0.2.0
          

        Default React application

      5. Use the CTRL+C key combination to stop Bun when you are finished viewing the application.

      6. Add an NPM package to your project. You can do so using the bun add command followed by the package name.

        This example uses the react-clock package, which allows you to easily render an analog clock for your React application:

        bun add react-clock
        
      7. The src/App.jsx file is the basis for the default React application. Open the file and incorporate the react-clock:

        nano src/App.jsx
        
      8. Replace the contents of src/App.jsx with the example file below. You can see the relatively simple modifications made to this file to incorporate the react-clock. The modified areas are prefaced with explanatory comments:

        File: src/App.jsx
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        
        import logo from "./logo.svg";
        import "./App.css";
        
        // Import React modules to be used by react-clock.
        import React, { useEffect, useState } from 'react';
        
        // Import react-clock and its CSS file.
        import Clock from 'react-clock';
        import 'react-clock/dist/Clock.css';
        
        function App() {
            // Define a state variable for the clock value; initialize it with the
            // current date-time.
            const [clockValue, setValue] = useState(new Date());
        
            // Define an effect that updates the clock's value periodically.
            useEffect(() => {
                const clockInterval = setInterval(() => setValue(new Date()), 1000);
        
                return () => {
                    clearInterval(clockInterval);
                };
            }, []);
        
            // Add to the default layout a <Clock/> tag for rendering the clock;
            // give it the clockValue to display.
            return (
                <div className="App">
                    <header className="App-header">
                        <img src={logo} className="App-logo" alt="logo" />
                        <h3>Welcome to React!</h3>
                        <Clock value={clockValue} />
                    </header>
                </div>
            );
        }
        
        export default App;
      9. Press CTRL+X to exit Nano, then Y to save, and Enter to confirm.

      10. Start up the application with Bun again:

        bun dev
        

        Once again, you should be able to visit the project by navigating to localhost:3000 in a web browser. Now you should see the default application modified with an analog clock.

        React application with an analog clock

      Conclusion

      Now that you have a footing with the Bun runtime, you can start exploring and seeing all it has to offer. With its built-in bundling and transpiling, you can create and execute projects with simpler tooling, plus the benefits of Bun’s incredible performance.

      Keep learning about Bun through the links below, as well as through the
      official documentation.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      How to Revert the Last Git Commit


      Git is a widely used Version Control System (VCS) known for its versatility. Git utilizes local clones of central repositories to bring more effective collaboration. It also keeps track of all the committed changes along the way, so things are readily recoverable.

      You might need that recoverability after an inadvertent commit, or to undo the most recent commit for any reason. Git has the ability to revert the last commit, and this tutorial shows you exactly how. It covers methods using both the revert and reset commands, and explains the differences.

      Learn more about Git generally in our guide
      Git vs SVN: Pros and Cons of Each Version Control System.

      For a more general, and thorough, coverage of reverting Git commits, take a look at our guide on
      How to Undo a Git Commit.

      Before You Begin

      This guide gives example output for the commands it describes. To get the best effect, you can follow along using a similar Git repository.

      These next few steps set you up with an example Git repository similar to the one used for the examples in this tutorial. The commit IDs may be different, but the contents of the repository should otherwise be the same.

      The steps presume you have already installed Git and done basic configuration (e.g. user email address and name). If you have not done this yet, you can learn how in our guide
      How to Install Git and Clone a GitHub Repository.

      1. Create a new directory for your Git repository, and change into that directory. Here, the new directory, git-example is created in the current user’s home directory:

        mkdir ~/git-example
        cd ~/git-example
        

        From here on, you should execute the given commands while working in this directory.

      2. Initialize the new Git repository:

        git init
        
      3. Use the touch command to create some new empty files:

        touch example-file-1.txt
        touch example-file-2.txt
        
      4. Add the files to the Git staging area, then commit the staged changes:

        git add .
        git commit -m "Initialized repo."
        
      5. Make some changes to the first file, adding some content to it. Then stage and commit those changes:

        echo "Some example text for the first file." >> example-file-1.txt
        git add example-file-1.txt
        git commit -m "Added text to first file."
        
      6. Do the same for the second file:

        echo "Some example text for the second file." >> example-file-2.txt
        git add example-file-2.txt
        git commit -m "Added text to second file."
        
      7. You now have a Git repository with a couple of files and several commits, which you can see listed with:

        git log --oneline
        
        f4391b2 (HEAD -> master) Added text to second file.
        e3c534a Added text to first file.
        0b24777 Initialized repo.

      How to Use revert on the Last Git Commit

      Git’s revert command undoes a commit by comparing the changes made in that commit to the repository’s previous state. The command then creates a new commit that reverts the changes.

      Thus, to use revert to undo the last commit, you first need the ID for that commit. You can get this with the log command. Here, the command is used with the --oneline option to make each commit display on a single line:

      git log --oneline
      
      f4391b2 (HEAD -> master) Added text to second file.
      e3c534a Added text to first file.
      0b24777 Initialized repo.

      The line at the top of the screen, with an ID of f4391b2 in this example, represents the last commit.

      From there, you can revert that commit using the revert command with that commit’s ID, as in:

      git revert f4391b2
      

      Git starts a new commit to revert the changes. It may present you with a text editor allowing you to edit the description for the new commit. When you are satisfied with the description, exit the text editor to complete the reversion.

      [master e86542a] Revert "Added text to second file."
       1 file changed, 1 deletion(-)

      Use the log command again, and you can see that there is now a new commit to revert the previous commit:

      git log --oneline
      
      e86542a (HEAD -> master) Revert "Added text to second file."
      f4391b2 Added text to second file.
      e3c534a Added text to first file.
      0b24777 Initialized repo.

      You can even check the modified file to see that the changes have been reversed. In this case, that is example-file-2.txt:

      cat example-file-2.txt
      

      How to Use reset to Undo Git Commits

      Git’s reset command can also be used to revert the last commit. The command is more radical than revert and works by removing commits entirely from the repository’s commit history. Essentially, reset “rewinds” you to a previous commit, eliminating later commits and history along the way.

      With the reset command, you have access to the HEAD~1 alias. This alias stands in for the ID of the previous commit, providing easy access when trying to revert to the last commit.

      The reset command comes with three flags that define how the command deals with changed files in the working directory and staging area.

      • Use the --soft option to roll back to a previous commit, while preserving file changes in the working directory and staging area.

        git reset --soft HEAD~1
        
      • Use the --hard option to likewise roll back to a previous commit. However, this option results in all file changes being reverted as well. Changes to files in the working directory as well as staged changes are both discarded.

        git reset --hard HEAD~1
        
      • Use the --mixed option to, again, roll back to a previous commit. Here, a middle ground is adopted for file changes. As with the --hard option, changes made to files in the working directory are discarded. However, like the --soft option, staged changes are preserved.

        git reset --mixed HEAD~1
        

      After any of the above reset commands, you can see that the last commit has been removed from the Git commit history:

      git log --oneline
      
      e3c534a (HEAD -> master) Added text to first file.
      0b24777 Initialized repo.

      The difference is that, if you ran the --soft option with the command, you can still find the changes to the file in the working directory. For this example, that is the example-file-2.txt file:

      cat example-file-2.txt
      
      Some example text for the second file.

      reset vs revert

      The main difference between the revert and reset commands is the commit history.

      The revert command aims to maintain a full commit history, undoing a commit by assessing changes and making a new commit that reverses them. This actually means that the revert command adds to the commit history. It gives you full transparency to past commits and their reversions.

      The reset command, on the other hand, discards commits even from the commit history, making them impossible to recover later. And reset can even do the same for local file changes. This option keeps you from seeing reversions and the original commits that are reverted.

      Generally, it is recommended that you use revert for backing out a commit. It keeps a record of the removed commit and leaves the possibility of assessing and accessing the commit history later.

      By contrast, the reset command should be used sparingly. Take a good look at the situation to ensure that it cannot be remedied by the revert command before you make the decision to apply reset. The reset option might be preferred, however, for immediately undoing mistaken commits, when there is less chance that you need options for recovering the changes.

      Conclusion

      That covers all you need to revert recent Git commits. Moreover, the techniques covered in this tutorial can also help you manage Git commits more generally. The revert command can be useful for precisely removing past commits while retaining your commit history. The reset command, on the other hand, provides a more radical option, completely reverting a repository to a previous commit, including the commit history.

      To keep learning, refer to the links at the beginning of this guide. These give you more on Git generally as well as more on the commands covered in this tutorial.

      You may also want to look at our entire lineup of
      guides on version control. These cover everything from the fundamentals to particular use cases, and provide steps to deepen your version control knowledge.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Installing Countly Community Edition on Ubuntu 20.04


      The Countly analytics platform offers an alternative to the ubiquitous Google Analytics. In contrast to Google Analytics, Countly puts more emphasis on privacy and an all-in-one feature set. Countly’s data gathering offers compliance with GDPR, HIPAA, and other privacy standards. Meanwhile, it provides not just visitor analytics, but also a wider range of analytics related to marketing.

      This tutorial shows you how to start using Countly for your analytics needs. Countly Community Edition is free to use, and it runs in a self-hosted server environment. Through this guide, you can learn all the steps needed to get your own Countly server up and tracking activity on your applications.

      Before You Begin

      1. Familiarize yourself with our
        Getting Started with Linode guide, and complete the steps for setting your Linode’s hostname and timezone.

      2. This guide uses sudo wherever possible. Complete the sections of our
        How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        Debian / Ubuntu

        sudo apt update && sudo apt upgrade

        AlmaLinux / CentOS Stream / Fedora / Rocky Linux

      Note

      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Users and Groups guide.

      Countly provides several installation options, which you can review in the link provided at the end of this tutorial.

      This guide covers the method using the Countly server GitHub repository, which tends to be straightforward as a result of the included installation script.

      These instructions are intended for and have been tested on Ubuntu systems. However, they may work on Debian and CentOS as well. Just be sure to make the necessary substitutions where relevant.

      After the steps on installing Countly, the tutorial includes instructions for two optional setup features to potentially improve your Countly experience: DNS and SSL.

      Installing Countly from the GitHub Repository

      These steps show you how to download the Git repository for Countly and use the included installation script. It also includes the steps you need to configure NGINX to properly serve your Countly interface.

      1. Clone the Countly server GitHub repository. This example clones the repository to the current user’s home directory. The process creates a new subdirectory there, countly-server:

        git clone https://github.com/Countly/countly-server.git
      2. The included installation script requires root access for the installation, so you should first switch to a superuser shell:

      3. Navigate to the subdirectory where the script is held:

        cd /home/example-user/countly-server/bin
      4. Run the installation script:

      5. Afterward, you can exit the superuser shell:

      6. Replace the default NGINX configuration with Countly’s
        own NGINX configuration file. Typically, you can find the default configuration file at /etc/nginx/sites-available/default. However, if this is a brand-new installation, you may have to create it:

        sudo mkdir /etc/nginx/sites-available
        sudo nano /etc/nginx/sites-available/default

        Additionally, you should extend the server_name property with the domain name and/or remote IP address you intend to use to access your Countly server. For instance, this example adds the domain name example.com and the remote IP address 192.0.2.0:

        File: /etc/nginx/sites-available/default
        1
        2
        3
        4
        5
        6
        
        server {
            listen   80;
            listen   [::]:80 ipv6only=on;
            server_name  localhost example.com 192.0.2.0;
        
            access_log  off;
      7. Open the HTTP port (80) on your server’s firewall. Typically, the firewalls on Ubuntu and Debian systems are managed with UFW. Using it, you can open the HTTP port with:

        sudo ufw allow http
        sudo ufw reload
      8. Access your Countly instance by navigating to one of the enabled addresses (that is, the server_name values from the NGINX configuration) in your web browser.

      (Optional) Assign Countly DNS

      Countly does not require you to use DNS for your server. However, doing so can make your Countly instance easier to access. It gives you access to your instance via a custom domain name, rather than just the remote IP address.

      To set up DNS on a Linode server, refer to our collection of guides on the
      Linode DNS manager. The process there is straightforward and can have your server running through a DNS quickly.

      (Optional) Assigning Countly TLS via Let’s Encrypt

      Another optional step is giving your Countly instance an SSL certificate. Doing so secures and encrypts its traffic using HTTPS.

      The following steps show you how to apply an SSL certificate to Countly using
      Certbot. Certbot allows you to easily request and download free certificates from
      Let’s Encrypt.

      1. Open the HTTPS port on your system’s firewall. Like above, you can do this using UFW with the HTTPS keyword:

        sudo ufw allow https
        sudo ufw reload
      2. Update the
        Snap app store. Snap provides application bundles that work across major Linux distributions and comes by default with all Ubuntu releases since 16.04:

        sudo snap install core && sudo snap refresh core
      3. Remove any existing Certbot installation:

      4. Install Certbot:

        sudo snap install --classic certbot
      5. Download a certificate using standalone verification. When prompted, accept the terms of service, enter an email address for notifications about certificate renewals, and enter your Countly server’s domain name:

        sudo certbot certonly --standalone

        Certbot outputs the location from which the new certificate can be accessed. Typically, it stores the required files in the following directory, replacing example.com with your domain name: /etc/letsencrypt/live/example.com.

      6. Access the NGINX site configuration again, and make the following modifications to the beginning of the file.

        These changes first add a server for port 80 that redirects traffic to the HTTPS URL. Then they alter the existing server definition to listen on port 443, the HTTPS port, and to use the SSL certificate created above.

        Replace example.com in this example with your server’s domain name:

        File: /etc/nginx/sites-available/default
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        
        server {
                listen      80;
                server_name localhost;
                access_log  off;
                rewrite ^ https://$host$request_uri? permanent;
        }
        
        server {
                listen   443 ssl;
                server_name  localhost example.com;
        
                ssl_certificate      /etc/letsencrypt/live/example.com/fullchain.pem;
                ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;
        
                access_log  off;

      Now, when navigating to your Countly instance in a web browser, you should be redirected to the HTTPS URL.

      You can optionally also add your server’s remote IP address to the NGINX configuration above and use that as well to access Countly. However, you may receive a certificate warning in your browser. This is because the certificate was issued for your server’s domain name, not its IP address.

      How to Navigate the Countly Server Interface

      With your Countly instance up and running, you are ready to start setting it up for use. This next series of sections first covers the initial setup within the Countly interface.

      Further on, you can set up a Countly client SDK within your application and see it begin gathering your analytics.

      Creating an Administrator Account and Logging In

      When you first access Countly, you’re presented with a form to register an administrator user for your instance. Keep track of the login information you create here, as this user has administrative control within the Countly instance.

      Countly registration page

      Accessing the address for your Countly instance after this initial setup directs you to the login page.

      Countly login page

      Adding an Application to the Countly Dashboard

      Submitting the form to create your administrator account automatically directs you to a page to create a new application for your Countly instance. Here, you are entering the name and some descriptive information about the application.

      Creating a new application in Countly

      You can also reach this form later from the Countly dashboard by selecting the Add new app button in the upper right.

      Later, you can use the application key created by this process to associate a Countly client with your Countly server instance. Doing so then directs analytics from that client to Countly’s dashboard for the application.

      Accessing the Countly Dashboard

      From there you are directed to your Countly dashboard, the same page you land on for subsequent logins.

      Countly dashboard

      Here, you can survey the analytics generated by your Countly instance and manage all aspects of your Countly operations. You can navigate between and create application entries, and within each, view analytics for visits, events, and more.

      How to Set Up the Countly Client for Analytics

      To have Countly start collecting analytics, you need to embed one of its client SDKs within your application.

      Countly has numerous client SDKs available to fit your needs, from web and mobile apps, to the desktop, server, and beyond. You can see Countly’s
      full list of client SDKs for more information on how to download and operate each.

      To get you started and to demonstrate, the rest of this section walks you through an example using Countly’s web application SDK. It covers how you can make the client available for your web application and even includes example code to embed it. If you don’t have a web application ready, follow our guide
      Deploy a Static Site using Hugo and Object Storage.

      1. Ensure your web application’s client-side code includes or has access to the Countly web SDK file. This can be done multiple ways:

        • The SDK is automatically hosted alongside your Countly instance. Assuming your server’s domain is example.com, you can find the SDK at: example.com/sdk/web/countly.min.js.

        • Additionally, the file itself can be found among the Countly server files. Starting from the base Countly server directory, the SDK file is located at frontend/express/public/sdk/web/countly.min.js. You can then copy that file to an appropriate directory with your web application’s client-side code.

        • The Countly SDK can also be accessed from Countly’s own CDN, which you can learn about in their
          web SDK documentation.

        For these steps, it is assumed that you made a copy of the countly.min.js file from Countly’s server files. The steps also assume that you have added that file to a lib subdirectory within your client-side code.

      2. Add the following code to the head section of one of your application’s web pages.

        Replace EXAMPLE_COUNTLY_APP_KEY with the App Key found in your Countly instance. Likewise, replace https://example.com with your Countly server’s URL or IP address (preceded by http://, or ‘https:// if you set up SSL).

        File: index.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        
        <!-- [...] -->
        <script type='text/javascript'>
        
        // Initialize variables to be used by the Countly client.
        var Countly = Countly || {};
        Countly.q = Countly.q || [];
        
        // Provide the application key from the Countly dashboard.
        Countly.app_key = 'EXAMPLE_COUNTLY_APP_KEY';
        
        // Provide the URL for your Countly server instance.
        Countly.url = 'https://example.com';
        
        // These next two start pushing function calls to queue. Both
        // are recommended configurations.
        
        // Track sessions automatically.
        Countly.q.push(['track_sessions']);
        // Track web page views automatically.
        Countly.q.push(['track_pageview']);
        
        // Load the Countly script asynchronously.
        (function() {
            var cly = document.createElement('script'); cly.type = 'text/javascript';
            cly.async = true;
        
            // Replace the URL here with the location of your Countly client SDK file.
            cly.src = 'lib/countly.min.js';
            cly.onload = function(){Countly.init()};
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(cly, s);
        })();
        </script>
        <!-- [...] -->

        Note

        Alternatively, you can have Countly automatically generate this code specifically for your applications. Click Management (the wrench icon) in the left-hand toolstrip, then Applications. Choose your application and scroll all the way down to the blue box titled “Need some help with SDK integration?”. Click the Web button and you should be redirected to an address that starts with code.count.ly/integration-web.html. From here, choose where you want to retrieve the countly.min.js file and what features you want to use. When done, click Generate code for code that’s custom-tailored for your application.

      3. Begin incorporating Countly event calls into your application. Here is an example of one such call, used for a button on the pages:

        File: index.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        
        <html>
        <head>
        <!-- [...] -->
        <script type='text/javascript'>
        function exampleButtonClicked(ob){
          Countly.q.push(['add_event',{
            key:"asyncButtonClick",
            segmentation: {
              "id": ob.id
            }
          }]);
        }
        </script>
        <!-- [...] -->
        </head>
        <body>
        <!-- [...] -->
        <input type="button" id="exampleButton" onclick="exampleButtonClicked(this)" value="Click This Button">
        <!-- [...] -->
        </body>
        </html>

      Navigating to your web application should now generate page views in Countly. Activating an event, like clicking the button in the above example, similarly now shows in Countly.

      Countly page visitors

      Countly page events

      Conclusion

      You are now ready to run your application’s analytics with Countly. With your own Countly server set up and the client embedded, you can begin diving deeper into your Countly configuration. Take a look through the
      Countly documentation to learn all the possibilities and see more of what Countly is capable of.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link