Node.js >= 16.0.0
required
Insights library can be used on the backend as a Node.js module.
npm install search-insights
# or
yarn add search-insights
Initializing the library is optional, as you can specify the credentials for each event when sending them. This gives you the flexibility to manage your Algolia credentials on a per-event basis, without having to configure them upfront.
const aa = require("search-insights");
// Optional: configure default Algolia credentials for events
aa("init", {
appId: "APPLICATION_ID",
apiKey: "SEARCH_API_KEY"
});
On the Node.js environment, unlike the browser environment, a user token (required userToken
and optional authenticatedUserToken
) must be specified when sending any event.
// Anonymous user ID
aa("clickedObjectIDs", {
userToken: "ANONYMOUS_ID"
// ...
});
// Authenticated user ID
aa("clickedObjectIDs", {
userToken: "ANONYMOUS_ID",
authenticatedUserToken: "USER_ID"
// ...
});
If you want to customize the way to send events, you can create a custom Insights client.
// via ESM
import { createInsightsClient } from "search-insights";
// OR in commonJS
const { createInsightsClient } = require("search-insights");
// OR via the UMD
const createInsightsClient = window.AlgoliaAnalytics.createInsightsClient;
function requestFn(url, data) {
const serializedData = JSON.stringify(data);
const { protocol, host, path } = require("url").parse(url);
const options = {
protocol,
host,
path,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": serializedData.length
}
};
const { request: nodeRequest } =
url.indexOf("https://") === 0 ? require("https") : require("http");
const req = nodeRequest(options);
req.on("error", (error) => {
console.error(error);
});
req.write(serializedData);
req.end();
}
const aa = createInsightsClient(requestFn);