@optic7409/resolvo-analytics
Version:
Simplified analytics client library for Next.js with automatic SSR handling, one-line integration, and comprehensive tracking
71 lines (70 loc) • 2.44 kB
JavaScript
export function detectEnvironment() {
const isClient = typeof window !== 'undefined';
const isServer = !isClient;
const isDevelopment = process.env.NODE_ENV === 'development';
const isProduction = process.env.NODE_ENV === 'production';
const isTest = process.env.NODE_ENV === 'test';
// Detect framework
let framework = 'unknown';
let routerType;
let nextJsVersion;
if (isClient) {
// Check for Next.js
if (typeof window !== 'undefined' && window.__NEXT_DATA__) {
framework = 'nextjs';
nextJsVersion = window.__NEXT_DATA__?.version;
// Detect router type (App Router vs Pages Router)
if (typeof window !== 'undefined') {
// Check if we're using App Router by looking for specific patterns
const hasAppRouter = document.querySelector('[data-nextjs-router]') !== null ||
window.__NEXT_DATA__?.page?.startsWith('/app/') ||
window.__NEXT_DATA__?.page?.includes('app/');
routerType = hasAppRouter ? 'app' : 'pages';
}
}
// Check for React
else if (typeof window !== 'undefined' && window.React) {
framework = 'react';
}
// Check for Vue
else if (typeof window !== 'undefined' && window.Vue) {
framework = 'vue';
}
// Check for Angular
else if (typeof window !== 'undefined' && window.angular) {
framework = 'angular';
}
}
return {
isClient,
isServer,
isDevelopment,
isProduction,
isTest,
framework,
routerType,
nextJsVersion
};
}
export function shouldEnableAnalytics(config) {
const env = detectEnvironment();
// Don't enable in test environment unless explicitly requested
if (env.isTest && config.environment !== 'test') {
return false;
}
// Don't enable on server unless explicitly requested
if (env.isServer && !config.debug) {
return false;
}
return true;
}
export function getDefaultConfig() {
const env = detectEnvironment();
return {
debug: env.isDevelopment,
environment: env.isDevelopment ? 'development' : 'production',
ssr: false, // Default to false for safety
autoInitialize: true,
apiUrl: 'https://www.resolvo.com/api/v1/analytics'
};
}