Overview
Installing the Kissmetrics tracking code is the first step to implementing behavioral analytics on your website or application. The tracking code loads asynchronously to ensure it doesn't impact your site's performance, and it needs to be present on every page where you want to track user behavior.
This guide covers multiple installation methods including direct installation, tag managers, and framework-specific implementations. Choose the method that best fits your tech stack and deployment workflow.
Getting Your API Key
Before installation, you need your Kissmetrics API key:
- Log in to your Kissmetrics account at app.kissmetrics.com
- Navigate to Settings or Product Settings
- Find your API key (format:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) - Copy the API key for use in the installation code
Keep your API key secure. While it's visible in client-side code, treat it as sensitive information.
Direct JavaScript Installation
The most common installation method is adding the JavaScript snippet directly to your HTML.
Standard Installation
Add this code to the <head> section of every page on your website:
<script type="text/javascript">
var _kmq = _kmq || [];
var _kmk = _kmk || 'YOUR_API_KEY'; // Replace with your actual API key
function _kms(u){
setTimeout(function(){
var d = document, f = d.getElementsByTagName('script')[0],
s = d.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = u;
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//scripts.kissmetrics.io/' + _kmk + '.js');
_kms('//scripts.kissmetrics.io/km.js');
</script>
Important: Replace YOUR_API_KEY with your actual Kissmetrics API key.
Why This Code Works
_kmq = _kmq || []: Creates the tracking queue array if it doesn't exist_kmk: Stores your API key_kms(): Asynchronously loads the Kissmetrics script- The script loads without blocking page rendering
- Events can be queued before the script fully loads
Installation Best Practices
Place in <head> Section:
<!DOCTYPE html>
<html>
<head>
<title>Your Website</title>
<!-- Kissmetrics Tracking Code -->
<script type="text/javascript">
var _kmq = _kmq || [];
var _kmk = _kmk || 'your-api-key-here';
function _kms(u){
setTimeout(function(){
var d = document, f = d.getElementsByTagName('script')[0],
s = d.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = u;
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//scripts.kissmetrics.io/' + _kmk + '.js');
</script>
<!-- End Kissmetrics -->
<!-- Other head content -->
</head>
<body>
<!-- Page content -->
</body>
</html>
Install on Every Page: The tracking code must be present on all pages where you want to track activity. For most websites, this means adding it to your main template or layout file.
Tag Manager Installation
Tag managers provide a centralized way to manage tracking scripts without modifying your website code directly.
Google Tag Manager
Step 1: Create a New Tag
- Log in to Google Tag Manager
- Go to Tags → New
- Click Tag Configuration
Step 2: Configure the Tag
- Choose tag type: Custom HTML
- Paste the Kissmetrics tracking code:
<script type="text/javascript">
var _kmq = _kmq || [];
var _kmk = _kmk || 'YOUR_API_KEY';
function _kms(u){
setTimeout(function(){
var d = document, f = d.getElementsByTagName('script')[0],
s = d.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = u;
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//scripts.kissmetrics.io/' + _kmk + '.js');
</script>
Step 3: Set Trigger
- Click Triggering
- Select All Pages (or create a custom trigger)
- Save the trigger
Step 4: Name and Save
- Name the tag: "Kissmetrics Tracking"
- Save the tag
Step 5: Test and Publish
- Use GTM Preview mode to test
- Verify events are tracking
- Submit and publish when ready
Segment
If you're using Segment, enable Kissmetrics as a destination:
- Log in to Segment
- Go to Destinations
- Add Destination → Kissmetrics
- Enter your Kissmetrics API key
- Enable the integration
Segment will automatically forward events to Kissmetrics using their naming conventions.
Tealium
Step 1: Add Tag
- Go to Tags → Add Tag
- Select "Generic Tag"
Step 2: Configure
- Title: "Kissmetrics"
- Tag Type: "Custom Container"
- Paste Kissmetrics code in the code field
Step 3: Set Scope
- Scope: All pages or specific pages
- Save and publish
Framework-Specific Implementations
React
For React applications, initialize Kissmetrics in your main app component:
// App.js or index.js
import { useEffect } from 'react';
function App() {
useEffect(() => {
// Initialize Kissmetrics
window._kmq = window._kmq || [];
window._kmk = 'YOUR_API_KEY';
const script = document.createElement('script');
script.src = `//scripts.kissmetrics.io/${window._kmk}.js`;
script.async = true;
document.head.appendChild(script);
// Identify user if logged in
if (window.currentUser) {
window._kmq.push(['identify', window.currentUser.email]);
}
}, []);
return (
<div className="App">
{/* Your app content */}
</div>
);
}
export default App;
React Router Page Tracking:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function useKissmetricsPageTracking() {
const location = useLocation();
useEffect(() => {
window._kmq.push(['record', 'Viewed Page', {
'Page Path': location.pathname,
'Page URL': window.location.href
}]);
}, [location]);
}
// Use in your app
function App() {
useKissmetricsPageTracking();
// ...rest of app
}
Vue.js
Initialize in your main.js file:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
// Initialize Kissmetrics
window._kmq = window._kmq || [];
window._kmk = 'YOUR_API_KEY';
const script = document.createElement('script');
script.src = `//scripts.kissmetrics.io/${window._kmk}.js`;
script.async = true;
document.head.appendChild(script);
const app = createApp(App);
// Vue Router tracking
app.config.globalProperties.$kmTrack = (event, properties) => {
window._kmq.push(['record', event, properties]);
};
app.mount('#app');
Vue Router Integration:
import { createRouter } from 'vue-router';
const router = createRouter({
// ... routes
});
router.afterEach((to, from) => {
window._kmq.push(['record', 'Viewed Page', {
'Page Path': to.path,
'Page Name': to.name
}]);
});
Angular
Add to your main component or app.component.ts:
// app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
ngOnInit() {
this.initializeKissmetrics();
}
initializeKissmetrics() {
(window as any)._kmq = (window as any)._kmq || [];
(window as any)._kmk = 'YOUR_API_KEY';
const script = document.createElement('script');
script.src = `//scripts.kissmetrics.io/${(window as any)._kmk}.js`;
script.async = true;
document.head.appendChild(script);
}
}
Next.js
Add to _app.js or _app.tsx:
// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
// Initialize Kissmetrics
window._kmq = window._kmq || [];
window._kmk = 'YOUR_API_KEY';
const script = document.createElement('script');
script.src = `//scripts.kissmetrics.io/${window._kmk}.js`;
script.async = true;
document.head.appendChild(script);
}, []);
useEffect(() => {
const handleRouteChange = (url) => {
window._kmq.push(['record', 'Viewed Page', {
'Page URL': url
}]);
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
}
export default MyApp;
WordPress Installation
Manual Installation
- Go to Appearance → Theme Editor
- Select your theme's header.php
- Add the Kissmetrics tracking code before the closing
</head>tag - Update the file
Note: Theme updates will overwrite this change. Use a child theme or plugin method instead.
Plugin Method (Recommended)
- Install "Insert Headers and Footers" or similar plugin
- Go to Settings → Insert Headers and Footers
- Paste Kissmetrics code in the "Scripts in Header" section
- Save
Verification
After installation, verify that Kissmetrics is working correctly.
Browser Console Check
Open your browser's developer console and run:
// Check if Kissmetrics object exists
console.log(typeof _kmq);
// Should output: "object"
// Check the queue
console.log(_kmq);
// Should show an array
// Test tracking an event
_kmq.push(['record', 'Test Event', {
'Test Property': 'Test Value'
}]);
Network Tab Verification
- Open browser DevTools
- Go to Network tab
- Reload your page
- Filter for "kissmetrics" or "trk.kissmetrics.io"
- You should see requests to Kissmetrics servers
Kissmetrics Dashboard Check
- Log in to Kissmetrics
- Go to the Live feed (if available)
- Perform actions on your site
- Events should appear in real-time or within a few minutes
Test Event
Send a test event to confirm tracking:
_kmq.push(['record', 'Installation Test', {
'Test Timestamp': new Date().toISOString(),
'Page URL': window.location.href
}]);
Check your Kissmetrics dashboard to see if the event appears.
Troubleshooting
Script Not Loading
Issue: Kissmetrics script fails to load.
Solutions:
- Check for HTTPS - use
https://instead of//in script URL:_kms('https://scripts.kissmetrics.io/' + _kmk + '.js'); - Verify API key is correct
- Check for ad blockers or privacy extensions blocking the script
- Verify your domain is whitelisted in Kissmetrics settings
- Check browser console for error messages
_kmq is Undefined
Issue: _kmq is undefined when trying to track events.
Solutions:
- Ensure the tracking code runs before any tracking calls
- Initialize the queue before use:
window._kmq = window._kmq || []; - Check if code is in the correct execution order
Events Not Appearing
Issue: Events tracked but not showing in dashboard.
Solutions:
- Wait 5-10 minutes for data processing
- Verify you're looking at the correct time range
- Check if user is identified for person-based events
- Verify API key matches your account
- Check for JavaScript errors preventing execution
Content Security Policy (CSP) Issues
Issue: CSP headers block Kissmetrics.
Solutions: Add Kissmetrics domains to your CSP:
Content-Security-Policy:
script-src 'self' scripts.kissmetrics.io;
connect-src 'self' trk.kissmetrics.io;
Best Practices
- Install Early: Place the tracking code in the
<head>to track as much user activity as possible - Install Once: Add the code to your main template/layout so it appears on all pages
- Test Before Deploy: Always test in a development or staging environment first
- Use Environment Variables: Store your API key in environment variables for different environments:
var _kmk = process.env.KISSMETRICS_API_KEY || 'YOUR_API_KEY'; - Monitor After Deployment: Check your Kissmetrics dashboard after deployment to ensure data is flowing
- Document Your Implementation: Keep records of where and how the tracking code is installed
- Use Version Control: Treat tracking code like any other code - commit it to version control
Next Steps
After successful installation:
- Identify Users - Set up user identification
- Track Events - Implement event tracking
- Set User Properties - Add user properties
- Configure Cross-Domain Tracking - If you have multiple domains
Your Kissmetrics implementation is now ready to start capturing valuable user behavior data.