Introduction to analytics-node
`analytics-node` is a powerful library designed to help you seamlessly integrate your applications with the Segment API. It enables you to collect and send analytics data from your Node.js applications in real-time. This library is essential for developers looking to gain valuable insights and optimize their applications based on user data.
Getting Started
To get started with `analytics-node`, you need to install it via npm:
npm install analytics-node
API Examples
Initializing the Client
const Analytics = require('analytics-node'); const analytics = new Analytics('YOUR_WRITE_KEY');
Tracking Events
Track events to capture user actions:
analytics.track({ userId: 'user123', event: 'Item Purchased', properties: { item: 'T-shirt', price: 19.99 } });
Identifying Users
Identify users with unique IDs and traits:
analytics.identify({ userId: 'user123', traits: { name: 'John Doe', email: 'john.doe@example.com' } });
Group Users
Group users by common traits or company association:
analytics.group({ userId: 'user123', groupId: 'company123', traits: { name: 'Awesome Company', industry: 'SaaS' } });
Page Views
Record page views in single-page applications:
analytics.page({ userId: 'user123', category: 'Docs', name: 'Analytics API', properties: { url: 'https://example.com/docs/analytics' } });
Screen Views
Track screen views in mobile applications:
analytics.screen({ userId: 'user123', category: 'Mobile', name: 'Home Screen' });
Alias
Alias is used to merge two user identities:
analytics.alias({ previousId: 'temporary_id', userId: 'authenticated_id' });
Flushing Data
Ensure all queued messages are sent before exiting the application:
analytics.flush((err, batch) => { if (err) { console.error('Error:', err); } else { console.log('Batch:', batch); } });
Application Example
Here is a simple Express.js application that uses `analytics-node` to track user events:
const express = require('express'); const Analytics = require('analytics-node'); const app = express(); const analytics = new Analytics('YOUR_WRITE_KEY'); app.use(express.json()); app.post('/track-purchase', (req, res) => { const { userId, item, price } = req.body; analytics.track({ userId: userId, event: 'Item Purchased', properties: { item, price } }); res.send('Purchase tracked successfully'); }); app.post('/identify-user', (req, res) => { const { userId, traits } = req.body; analytics.identify({ userId: userId, traits: traits }); res.send('User identified successfully'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
With this application, you can easily track purchases and identify users by making POST requests to the respective endpoints.
Now you are well-equipped to leverage the power of `analytics-node` in your Node.js applications for efficient analytics and user tracking.
Hash: 34004cffaa44fb35dbc3cd7ae3352da890745cc376587aa0df43957f23126a3b