### Install dependencies Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Remove the old package and install the new one. ```bash pnpm remove react-yandex-metrika pnpm add @artginzburg/next-ym ``` -------------------------------- ### Initialize YandexMetricaProvider for App Router Source: https://context7.com/artginzburg/next-ym/llms.txt Wrap your application's root layout with YandexMetricaProvider to enable analytics. This example shows the setup for the App Router. ```tsx import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Install dependencies Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Remove the old package and install the new one using pnpm. ```bash pnpm remove react-yandex-metrika pnpm add @artginzburg/next-ym ``` -------------------------------- ### Install @artginzburg/next-ym Source: https://github.com/artginzburg/next-ym/blob/main/README.md Install the package using npm or pnpm. Requires Next.js 11+ and React 17+. ```bash pnpm add @artginzburg/next-ym ``` ```bash npm install @artginzburg/next-ym ``` -------------------------------- ### Initialize YandexMetricaProvider for Pages Router Source: https://context7.com/artginzburg/next-ym/llms.txt Wrap your application's root component with YandexMetricaProvider to enable analytics. This example shows the setup for the Pages Router. ```tsx import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function MyApp({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Yandex Metrica Provider Setup with Environment Variable Source: https://context7.com/artginzburg/next-ym/llms.txt Use the `YandexMetricaProvider` to automatically read the `tagID` from the `NEXT_PUBLIC_YANDEX_METRICA_ID` environment variable. No `tagID` prop is needed when the environment variable is set. ```tsx // No tagID prop needed when env var is set import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {/* tagID is automatically read from NEXT_PUBLIC_YANDEX_METRICA_ID */} {children} ); } ``` -------------------------------- ### Initialize analytics hook imports Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Setup the base imports for a centralized analytics hook. ```tsx // hooks/useAnalytics.ts 'use client'; import { useEcommerce, useMetrica } from '@artginzburg/next-ym'; import { useCallback } from 'react'; ``` -------------------------------- ### App Router Setup with YandexMetricaProvider Source: https://github.com/artginzburg/next-ym/blob/main/README.md Integrate Yandex Metrica into your Next.js App Router application by wrapping your root layout with YandexMetricaProvider. Pageviews are tracked automatically. ```tsx // app/layout.tsx import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Extend standardYMInitParameters Source: https://context7.com/artginzburg/next-ym/llms.txt Use standard Yandex Metrica initialization parameters as a base and extend them with custom options. This example shows how to add trackHash and defer. ```tsx import { standardYMInitParameters } from '@artginzburg/next-ym'; // standardYMInitParameters equals: // { // clickmap: true, // trackLinks: true, // accurateTrackBounce: true, // webvisor: true, // ecommerce: true, // } // Extend with custom options const customParams = { ...standardYMInitParameters, trackHash: true, defer: false, }; {children} ``` -------------------------------- ### Pages Router Setup with YandexMetricaProvider Source: https://github.com/artginzburg/next-ym/blob/main/README.md Integrate Yandex Metrica into your Next.js Pages Router application by wrapping your root component with YandexMetricaProvider. Pageviews are tracked automatically. ```tsx // pages/_app.tsx import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function MyApp({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Validate goal usage with TypeScript Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Examples of how TypeScript enforces correct parameters for goals. ```tsx reachGoal('signup'); // OK — no params reachGoal('signup', { foo: 1 }); // Error — signup takes no params reachGoal('purchase', { itemId: '1', ... }); // OK — all fields required reachGoal('purchase'); // Error — params required reachGoal('purchase', { itemId: '1' }); // Error — missing fields ``` -------------------------------- ### withMetricaProxy Source: https://context7.com/artginzburg/next-ym/llms.txt Next.js configuration wrapper to proxy the Yandex Metrica script. ```APIDOC ## withMetricaProxy ### Description A Next.js configuration wrapper that sets up a proxy for the Yandex Metrica script. This allows the script to be served from your own domain, helping to bypass Safari's Intelligent Tracking Prevention (ITP) by appearing as first-party. ``` -------------------------------- ### Track Product Detail Page View Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Fire a product view event when the detail page mounts. Guard against empty data and use a stable primitive as the dependency to avoid re-firing. ```tsx import { useEffect } from 'react'; import { useAnalytics } from './useAnalytics'; // components/ItemDetail.tsx const { trackItemView } = useAnalytics(); useEffect(() => { if (item) trackItemView(item); // eslint-disable-next-line react-hooks/exhaustive-deps -- track once per item, not on every object reference change }, [item?.id, trackItemView]); ``` -------------------------------- ### Configure Safari ITP Proxy Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Wraps the Next.js configuration to proxy Metrica scripts as first-party. ```ts // next.config.ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; const nextConfig = { /* your config */ }; export default withMetricaProxy(nextConfig); ``` -------------------------------- ### YandexMetricaProvider Configuration Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Demonstrates how to use the YandexMetricaProvider to conditionally render Yandex Metrica based on user consent, ensuring GDPR compliance. ```APIDOC ## YandexMetricaProvider Usage ### Description This example shows how to conditionally render the `YandexMetricaProvider` based on user consent. The provider is only mounted when `analyticsAllowed` is true, preventing network requests until consent is granted. ### Method Component Rendering (React) ### Endpoint N/A (Client-side component) ### Parameters #### Props for `YandexMetricaProvider` - **initParameters** (InitParameters) - Required - Initialization parameters for Yandex Metrica. Use `standardYMInitParameters` for recommended defaults. - **tagID** (number) - Optional - Yandex Metrica tag ID. Can be omitted if `NEXT_PUBLIC_YANDEX_METRICA_ID` environment variable is set. - **strategy** (ScriptProps['strategy']) - Optional - Next.js script loading strategy. Defaults to `afterInteractive`. - **shouldUseAlternativeCDN** (boolean) - Optional - If true, uses the alternative Yandex Metrica CDN. ### Request Example ```tsx 'use client'; import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; import { useConsent } from '@/hooks/useConsent'; export function AnalyticsGate({ children }: { children: React.ReactNode }) { const { analyticsAllowed } = useConsent(); if (!analyticsAllowed) return <>{children}; return ( {children} ); } ``` ### Response N/A (Component rendering) ### Success Response (200) N/A ### Response Example N/A ``` -------------------------------- ### Ecommerce Tracking with useEcommerce Hook Source: https://github.com/artginzburg/next-ym/blob/main/README.md Provides full typed ecommerce support via the `useEcommerce` hook. Requires `ecommerce: 'dataLayer'` in init parameters. ```APIDOC ## Ecommerce Tracking ### Description Full typed ecommerce support via the `useEcommerce` hook. Requires `ecommerce: 'dataLayer'` in init parameters (included in `standardYMInitParameters`). ### Initialization Example ```tsx import { useEcommerce } from '@artginzburg/next-ym'; // currencyCode is set once and applied to all calls const { trackClickProduct, trackAddItemToBasket, trackPurchase } = useEcommerce({ currencyCode: 'RUB', }); ``` ### Product Tracking Each product accepts: `id`, `name` (at least one required), and optional `brand`, `category`, `price`, `quantity`, `variant`, `coupon`, `discount`, `list`, `position`. #### Track Product List Impressions ```tsx trackImpressionsProduct({ products: [ { id: '123', name: 'T-Shirt', price: 1500, list: 'Homepage' }, { id: '456', name: 'Hoodie', price: 3500, list: 'Homepage' }, ], }); ``` #### Track Product Interactions (Click, View, Add to Cart, Remove from Cart) ```tsx // Track product click / detail view / add to cart / remove from cart // (all accept a single product) trackClickProduct({ product: { id: '123', name: 'T-Shirt' } }); trackViewProduct({ product: { id: '123', name: 'T-Shirt', price: 1500 } }); trackAddItemToBasket({ product: { id: '123', name: 'T-Shirt', price: 1500, quantity: 1 } }); trackRemoveItemFromBasket({ product: { id: '123', name: 'T-Shirt' } }); ``` ### Purchase Tracking ```tsx trackPurchase({ actionField: { id: 'ORDER-789', // required — order ID revenue: 5000, // optional — overrides sum of product prices coupon: 'SALE10', // optional goal_id: 12345678, // optional — Metrica goal number }, products: [ { id: '123', name: 'T-Shirt', price: 1500, quantity: 2 }, { id: '456', name: 'Hoodie', price: 2000, quantity: 1 }, ], }); ``` ### Promo Campaigns Tracking ```tsx trackPromoView({ promotions: [{ id: 'SUMMER_SALE', name: 'Summer Sale', creative: 'banner_1', position: 'top' }], }); trackPromoClick({ promotion: { id: 'SUMMER_SALE', name: 'Summer Sale' }, }); ``` ### All Ecommerce Methods | Method | Argument | Description | | --------------------------- | --------------------------------- | -------------------------------- | | `trackImpressionsProduct` | `{ products: Product[] }` | Product list was shown | | `trackClickProduct` | `{ product: Product }` | Product was clicked | | `trackViewProduct` | `{ product: Product }` | Product detail page viewed | | `trackAddItemToBasket` | `{ product: Product }` | Added to cart | | `trackRemoveItemFromBasket` | `{ product: Product }` | Removed from cart | | `trackPurchase` | `{ actionField, products }` | Order completed | | `trackPromoView` | `{ promotions: PromoCampaign[] }` | Promo banner shown | | `trackPromoClick` | `{ promotion: PromoCampaign }` | Promo banner clicked | | `pushToDataLayer` | raw ecommerce data | Escape hatch for custom payloads | ``` -------------------------------- ### Configure Metrica Proxy in Next.js Source: https://context7.com/artginzburg/next-ym/llms.txt Wraps the Next.js configuration to serve the Metrica script as first-party, helping bypass ITP. Automatically integrates with existing rewrites. ```ts // next.config.ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; const nextConfig = { reactStrictMode: true, // ... your other config options }; export default withMetricaProxy(nextConfig); // With existing rewrites const nextConfigWithRewrites = { reactStrictMode: true, async rewrites() { return [ { source: '/api/proxy/:path*', destination: 'https://api.example.com/:path*' }, ]; }, }; export default withMetricaProxy(nextConfigWithRewrites); // The Metrica proxy rewrite is automatically added to your existing rewrites ``` -------------------------------- ### Track Ecommerce Events with useEcommerce Hook Source: https://context7.com/artginzburg/next-ym/llms.txt Provides methods for tracking product impressions, clicks, cart actions, and purchases. Requires ecommerce initialization in the library settings. ```tsx import { useEcommerce } from '@artginzburg/next-ym'; function EcommerceExample() { const { trackImpressionsProduct, trackClickProduct, trackViewProduct, trackAddItemToBasket, trackRemoveItemFromBasket, trackPurchase, trackPromoView, trackPromoClick, pushToDataLayer, } = useEcommerce({ currencyCode: 'USD' }); // Track product list impressions const handleProductListView = () => { trackImpressionsProduct({ products: [ { id: 'SKU001', name: 'T-Shirt', price: 29.99, category: 'Clothing/Shirts', list: 'Homepage Featured' }, { id: 'SKU002', name: 'Hoodie', price: 59.99, category: 'Clothing/Outerwear', list: 'Homepage Featured' }, ], }); }; // Track product click const handleProductClick = () => { trackClickProduct({ product: { id: 'SKU001', name: 'T-Shirt', price: 29.99, position: 1 }, }); }; // Track product detail view const handleProductView = () => { trackViewProduct({ product: { id: 'SKU001', name: 'T-Shirt', price: 29.99, brand: 'BrandName', category: 'Clothing/Shirts', variant: 'Blue/Large', }, }); }; // Track add to cart const handleAddToCart = () => { trackAddItemToBasket({ product: { id: 'SKU001', name: 'T-Shirt', price: 29.99, quantity: 2, variant: 'Blue/Large' }, }); }; // Track remove from cart const handleRemoveFromCart = () => { trackRemoveItemFromBasket({ product: { id: 'SKU001', name: 'T-Shirt', quantity: 1 }, }); }; // Track completed purchase const handlePurchase = () => { trackPurchase({ actionField: { id: 'ORDER-12345', revenue: 89.98, coupon: 'SAVE10', goal_id: 98765432, // Optional Metrica goal number }, products: [ { id: 'SKU001', name: 'T-Shirt', price: 29.99, quantity: 2 }, { id: 'SKU003', name: 'Cap', price: 19.99, quantity: 1, discount: 5 }, ], }); }; // Track promo banner impressions const handlePromoView = () => { trackPromoView({ promotions: [ { id: 'SUMMER_SALE', name: 'Summer Sale', creative: 'banner_hero', position: 'top' }, { id: 'FREE_SHIP', name: 'Free Shipping', creative: 'banner_sidebar', position: 'sidebar' }, ], }); }; // Track promo banner click const handlePromoClick = () => { trackPromoClick({ promotion: { id: 'SUMMER_SALE', name: 'Summer Sale' }, }); }; return (
); } ``` -------------------------------- ### Initialize Ecommerce Tracking Hook Source: https://github.com/artginzburg/next-ym/blob/main/README.md Initializes the `useEcommerce` hook with a specified currency code. This hook provides methods for tracking various ecommerce events. ```tsx import { useEcommerce } from '@artginzburg/next-ym'; // currencyCode is set once and applied to all calls const { trackClickProduct, trackAddItemToBasket, trackPurchase } = useEcommerce({ currencyCode: 'RUB', }); ``` -------------------------------- ### Configure Safari ITP proxy Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Wrap your next.config.ts with withMetricaProxy to route scripts through your own domain. ```ts // next.config.ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; export default withMetricaProxy({ /* your config */ }); ``` -------------------------------- ### Customize provider initialization Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Spread custom options over the standard initialization parameters. ```tsx ``` -------------------------------- ### Track product detail views Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Fires a view event when a detail page mounts. Use a stable primitive like item ID as a dependency to avoid re-firing on object reference changes. ```tsx // components/ItemDetail.tsx const { trackItemView } = useAnalytics(); useEffect(() => { if (item) trackItemView(item); // eslint-disable-next-line react-hooks/exhaustive-deps -- track once per item, not on every object reference change }, [item?.id, trackItemView]); ``` -------------------------------- ### Configure YandexMetricaProvider with custom options Source: https://context7.com/artginzburg/next-ym/llms.txt Customize Yandex Metrica initialization parameters and script loading strategy. The tagID is optional if NEXT_PUBLIC_YANDEX_METRICA_ID environment variable is set. ```tsx {children} ``` -------------------------------- ### Implement ecommerce tracking Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Use the useEcommerce hook for typed ecommerce event tracking. ```tsx import { useEcommerce } from '@artginzburg/next-ym'; const { trackAddItemToBasket, trackPurchase } = useEcommerce({ currencyCode: 'RUB' }); trackAddItemToBasket({ product: { id: '123', name: 'T-Shirt', price: 1500, quantity: 1 } }); ``` -------------------------------- ### Swap event calls Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Replace the default ym import with the typed useMetrica hook. ```tsx import ym from 'react-yandex-metrika'; function BuyButton() { return ; } ``` ```tsx import { useMetrica } from '@artginzburg/next-ym'; function BuyButton() { const { reachGoal } = useMetrica(); return ; } ``` -------------------------------- ### Configure Safari ITP Proxy with next-ym Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Use this configuration to automatically set up a reverse proxy for Safari's ITP, routing scripts through your own domain. This is an optional step to prevent data loss due to Safari's tracking prevention. ```typescript // next.config.ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; export default withMetricaProxy({ /* your config */ }); ``` -------------------------------- ### Safari ITP Proxy Configuration Source: https://github.com/artginzburg/next-ym/blob/main/README.md Configures a built-in proxy to make the Metrica script appear as first-party, bypassing Safari's Intelligent Tracking Prevention. ```APIDOC ## Safari ITP Proxy ### Description Safari's Intelligent Tracking Prevention blocks third-party scripts from `mc.yandex.ru`. The built-in proxy makes the Metrica script appear as first-party. ### Configuration Example (`next.config.ts`) ```ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; const nextConfig = { /* your config */ }; export default withMetricaProxy(nextConfig); ``` ### Usage No extra props are needed. The provider auto-detects the proxy and uses it. ``` -------------------------------- ### Create comprehensive useAnalytics hook Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Combine ecommerce wrappers and goal tracking into a single hook for component usage. ```tsx export function useAnalytics() { const { reachGoal: _reachGoal, setUserID, notBounce } = useMetrica(); const { trackPurchase: _trackPurchase, trackViewProduct: _trackViewProduct, trackClickProduct: _trackClickProduct, trackImpressionsProduct: _trackImpressionsProduct, } = useEcommerce({ currencyCode: 'USD' }); // ... reachGoal wrapper from above ... /** Full purchase: ecommerce event + goal. */ const trackItemPurchase = useCallback( (item: ItemProduct) => { const product = toProduct(item); _trackPurchase({ actionField: { id: item.id, revenue: product.price }, products: [product], }); reachGoal('purchase', { itemId: item.id, type: item.type, category: item.category, price: product.price, }); }, [_trackPurchase, reachGoal], ); const trackItemView = useCallback( (item: ItemProduct) => _trackViewProduct({ product: toProduct(item) }), [_trackViewProduct], ); const trackItemClick = useCallback( (item: ItemProduct) => _trackClickProduct({ product: toProduct(item) }), [_trackClickProduct], ); /** Bulk impressions — call when a list of items renders. */ const trackItemImpressions = useCallback( (items: ItemProduct[]) => { if (items.length === 0) return; _trackImpressionsProduct({ products: items.map(toProduct) }); }, [_trackImpressionsProduct], ); const identifyUser = useCallback((userId: string) => setUserID(userId), [setUserID]); return { reachGoal, trackItemPurchase, trackItemView, trackItemClick, trackItemImpressions, identifyUser, notBounce, }; } ``` -------------------------------- ### Replace YMInitializer with YandexMetricaProvider Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Update the root component to use the new provider. ```tsx // pages/_app.tsx import { YMInitializer } from 'react-yandex-metrika'; export default function MyApp({ Component, pageProps }) { return ( <> ); } ``` ```tsx // pages/_app.tsx — or app/layout.tsx for App Router import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function MyApp({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Track Product List Impressions Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Track impressions when a product list is displayed. Use the list length as a dependency to avoid re-firing on every render. ```tsx import { useEffect } from 'react'; import { useAnalytics } from './useAnalytics'; // components/ItemList.tsx const { trackItemImpressions, trackItemClick } = useAnalytics(); useEffect(() => { trackItemImpressions(items); // eslint-disable-next-line react-hooks/exhaustive-deps -- fire only when the list size changes, not on every new array reference }, [items.length, trackItemImpressions]); return items.map((item) => (
trackItemClick(item)}> {item.title}
)); ``` -------------------------------- ### Configure Next.js with Metrica Proxy Source: https://github.com/artginzburg/next-ym/blob/main/README.md Configures the Next.js application to use a Metrica proxy for Safari ITP compatibility. This involves wrapping the Next.js config with `withMetricaProxy`. ```ts import { withMetricaProxy } from '@artginzburg/next-ym/config'; const nextConfig = { /* your config */ }; export default withMetricaProxy(nextConfig); ``` -------------------------------- ### Configure Yandex Metrica Tag ID via Environment Variables Source: https://context7.com/artginzburg/next-ym/llms.txt Set the Yandex Metrica tag ID using environment variables to avoid hardcoding values. When using `withMetricaProxy`, the `NEXT_PUBLIC_YM_PROXY_PATH` is automatically set. ```bash # .env.local NEXT_PUBLIC_YANDEX_METRICA_ID=12345678 # When using withMetricaProxy, this is automatically set: # NEXT_PUBLIC_YM_PROXY_PATH=/metrika-proxy.js ``` -------------------------------- ### YandexMetricaProvider Component Source: https://context7.com/artginzburg/next-ym/llms.txt The root provider component used to initialize Yandex Metrica and enable automatic pageview tracking across the application. ```APIDOC ## YandexMetricaProvider ### Description Wraps the application root to initialize Yandex Metrica. It handles automatic SPA navigation tracking and provides the context for tracking hooks. ### Parameters - **tagID** (number) - Optional - The Yandex Metrica counter ID. Defaults to NEXT_PUBLIC_YANDEX_METRICA_ID env var. - **initParameters** (object) - Optional - Configuration object for Yandex Metrica (e.g., clickmap, webvisor, ecommerce). - **strategy** (string) - Optional - next/script loading strategy (e.g., 'afterInteractive'). - **shouldUseAlternativeCDN** (boolean) - Optional - Toggle to use an alternative CDN for the script. ### Request Example {children} ``` -------------------------------- ### Configure environment variable Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Set the Yandex Metrica tag ID in your environment variables. ```env NEXT_PUBLIC_YANDEX_METRICA_ID=12345678 ``` -------------------------------- ### YandexMetricaProvider Props Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Detailed explanation of the available props for the YandexMetricaProvider component. ```APIDOC ## YandexMetricaProvider Props ### Description This section details the configurable properties for the `YandexMetricaProvider` component, allowing customization of Yandex Metrica initialization and script loading. ### Method Component Props ### Endpoint N/A ### Parameters #### Props - **tagID** (number) - Optional - Yandex Metrica tag ID. If not provided, the value of the `NEXT_PUBLIC_YANDEX_METRICA_ID` environment variable will be used. - **initParameters** (InitParameters) - Required - An object containing initialization parameters for Yandex Metrica. For recommended default settings, use the `standardYMInitParameters` export. - **strategy** (ScriptProps['strategy']) - Optional - Specifies the loading strategy for the Yandex Metrica script, compatible with Next.js's `script` component strategies (e.g., `beforeInteractive`, `afterInteractive`). Defaults to `afterInteractive`. - **shouldUseAlternativeCDN** (boolean) - Optional - When set to `true`, this prop instructs the provider to load the Yandex Metrica script from an alternative CDN URL. ### Request Example N/A ### Response N/A ### Success Response (200) N/A ### Response Example N/A ``` -------------------------------- ### Swap event calls to useMetrica hook Source: https://github.com/artginzburg/next-ym/blob/main/llms-full.txt Replace the default ym import with the typed reachGoal method from useMetrica. ```tsx import ym from 'react-yandex-metrika'; function BuyButton() { return ; } ``` ```tsx import { useMetrica } from '@artginzburg/next-ym'; function BuyButton() { const { reachGoal } = useMetrica(); return ; } ``` -------------------------------- ### Type-Safe Goal Tracking with `useAnalytics` Source: https://context7.com/artginzburg/next-ym/llms.txt Implement a type-safe wrapper for goal tracking to enforce correct parameters for each goal name at compile time. This hook ensures that when you call `reachGoal`, the correct parameters are passed based on the goal type. ```tsx 'use client'; import { useMetrica } from '@artginzburg/next-ym'; import { useCallback } from 'react'; // Define goal parameters map type GoalParams = { purchase: { itemId: string; price: number; category: string }; signup: undefined; login: undefined; add_to_cart: { itemId: string; quantity: number }; search: { query: string; results_count: number }; download: { file_name: string }; }; type Goal = keyof GoalParams; export function useAnalytics() { const { reachGoal: _reachGoal, setUserID, notBounce } = useMetrica(); // Type-safe reachGoal wrapper const reachGoal = useCallback( (goal: G, ...args: GoalParams[G] extends undefined ? [] : [GoalParams[G]]) => { _reachGoal(goal, args[0] as Record | undefined); }, [_reachGoal], ); return { reachGoal, setUserID, notBounce }; } // Usage - TypeScript enforces correct parameters function Component() { const { reachGoal } = useAnalytics(); reachGoal('signup'); // OK - no params required reachGoal('purchase', { itemId: '123', price: 99, category: 'Electronics' }); // OK // reachGoal('purchase'); // Error - params required // reachGoal('signup', { foo: 1 }); // Error - no params allowed return null; } ``` -------------------------------- ### Replace initializer component Source: https://github.com/artginzburg/next-ym/blob/main/docs/migrating-from-react-yandex-metrika.md Swap the old YMInitializer with the new YandexMetricaProvider. ```tsx // pages/_app.tsx import { YMInitializer } from 'react-yandex-metrika'; export default function MyApp({ Component, pageProps }) { return ( <> ); } ``` ```tsx // pages/_app.tsx — or app/layout.tsx for App Router import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym'; export default function MyApp({ Component, pageProps }) { return ( ); } ``` ```tsx ``` -------------------------------- ### Track Product Impressions Source: https://github.com/artginzburg/next-ym/blob/main/README.md Tracks product list impressions by accepting an array of product objects. Each product can include details like id, name, price, and list. ```tsx // Track product list impressions (accepts an array of products) trackImpressionsProduct({ products: [ { id: '123', name: 'T-Shirt', price: 1500, list: 'Homepage' }, { id: '456', name: 'Hoodie', price: 3500, list: 'Homepage' }, ], }); ``` -------------------------------- ### Track item impressions and clicks Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Tracks product list displays and clicks. Use the list length as a dependency to prevent unnecessary re-firing on array reference changes. ```tsx // components/ItemList.tsx const { trackItemImpressions, trackItemClick } = useAnalytics(); useEffect(() => { trackItemImpressions(items); // eslint-disable-next-line react-hooks/exhaustive-deps -- fire only when the list size changes, not on every new array reference }, [items.length, trackItemImpressions]); return items.map((item) => (
trackItemClick(item)}> {item.title}
)); ``` -------------------------------- ### YandexMetricaProvider Component Source: https://github.com/artginzburg/next-ym/blob/main/README.md The YandexMetricaProvider component is used to initialize Yandex Metrica. It supports conditional rendering for GDPR compliance and accepts various configuration props. ```APIDOC ## YandexMetricaProvider ### Description A React provider component that initializes Yandex Metrica. It defers network requests until mounted, making it suitable for consent-based tracking. ### Parameters #### Props - **tagID** (number) - Optional - Yandex Metrica tag ID. Can also be set via NEXT_PUBLIC_YANDEX_METRICA_ID env var. - **initParameters** (InitParameters) - Required - Initialization parameters. Use standardYMInitParameters for recommended defaults. - **strategy** (ScriptProps['strategy']) - Optional - next/script strategy. Default: afterInteractive. - **shouldUseAlternativeCDN** (boolean) - Optional - Whether to use the alternative CDN for loading the script. ``` -------------------------------- ### useEcommerce Hook Source: https://context7.com/artginzburg/next-ym/llms.txt React hook for tracking ecommerce events following Yandex Metrica's enhanced ecommerce specification. ```APIDOC ## useEcommerce Hook ### Description A React hook that provides methods to track ecommerce events such as product impressions, clicks, views, cart actions, and purchases. Requires `ecommerce: true` or `ecommerce: 'dataLayer'` in init parameters. ### Methods - **trackImpressionsProduct**: Tracks product list impressions. - **trackClickProduct**: Tracks a product click. - **trackViewProduct**: Tracks a product detail view. - **trackAddItemToBasket**: Tracks adding an item to the cart. - **trackRemoveItemFromBasket**: Tracks removing an item from the cart. - **trackPurchase**: Tracks a completed purchase. - **trackPromoView**: Tracks promo banner impressions. - **trackPromoClick**: Tracks a promo banner click. - **pushToDataLayer**: Pushes custom data to the data layer. ``` -------------------------------- ### Define typed goal parameters Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Create a map of goal names to their expected payloads to ensure compile-time safety. ```tsx type GoalParams = { // Conversions purchase: { itemId: string; type: string; category: string; price: number }; item_created_free: { itemId: string; type: string }; item_downloaded: { itemId: string }; // Payments top_up: { amount: number }; top_up_started: { amountCents: number }; // Auth signup: undefined; login: undefined; // Engagement review_submitted: { itemId: string; rating: number }; referral_link_copied: undefined; guidelines_uploaded: { fileName: string }; }; type Goal = keyof GoalParams; ``` -------------------------------- ### Execute Yandex Metrica Commands with ym Function Source: https://context7.com/artginzburg/next-ym/llms.txt Enables direct interaction with the global ym function for goals, page hits, and user parameters. Requires the tag ID as the first argument. ```ts import { ym } from '@artginzburg/next-ym'; const TAG_ID = 12345678; // Track a goal ym(TAG_ID, 'reachGoal', 'cta-click'); // Track goal with parameters ym(TAG_ID, 'reachGoal', 'purchase', { order_price: 99.99, currency: 'USD' }); // Track page hit manually ym(TAG_ID, 'hit', '/virtual-page', { title: 'Virtual Page Title', referer: 'https://example.com/previous-page', }); // Set user ID ym(TAG_ID, 'setUserID', 'user_12345'); // Send user parameters ym(TAG_ID, 'userParams', { UserID: 12345, subscription: 'premium' }); // Mark as not bounce ym(TAG_ID, 'notBounce'); // Track external link click ym(TAG_ID, 'extLink', 'https://external-site.com'); // Track file download ym(TAG_ID, 'file', 'https://example.com/files/document.pdf'); // Get client ID ym(TAG_ID, 'getClientID', (clientID) => { console.log('Metrica Client ID:', clientID); }); // Send first-party params for cross-device tracking ym(TAG_ID, 'firstPartyParams', { email: 'user@example.com', phone_number: '+1234567890', }); ``` -------------------------------- ### Domain-to-Product Mapping for Yandex Metrica Ecommerce Source: https://context7.com/artginzburg/next-ym/llms.txt Convert your application's domain objects to Yandex Metrica's ecommerce product format using a centralized converter function. This pattern helps in tracking e-commerce events like purchases, product views, and clicks accurately. ```tsx 'use client'; import { useEcommerce, useMetrica } from '@artginzburg/next-ym'; import { useCallback, useEffect } from 'react'; // Your domain model interface AppProduct { id: string; title: string; priceCents: number; type: 'PREMIUM' | 'BASIC'; category: string; } // Convert to Metrica format function toMetricaProduct(item: AppProduct) { return { id: item.id, name: `${item.type === 'PREMIUM' ? 'Premium' : 'Basic'}: ${item.title}`, price: item.priceCents / 100, category: item.category, variant: item.type, quantity: 1, }; } export function useAnalytics() { const { reachGoal } = useMetrica(); const { trackPurchase, trackViewProduct, trackClickProduct, trackImpressionsProduct } = useEcommerce({ currencyCode: 'USD' }); const trackItemPurchase = useCallback( (item: AppProduct) => { const product = toMetricaProduct(item); trackPurchase({ actionField: { id: `order_${Date.now()}`, revenue: product.price }, products: [product], }); reachGoal('purchase', { itemId: item.id, price: product.price }); }, [trackPurchase, reachGoal], ); const trackItemView = useCallback( (item: AppProduct) => trackViewProduct({ product: toMetricaProduct(item) }), [trackViewProduct], ); const trackItemClick = useCallback( (item: AppProduct) => trackClickProduct({ product: toMetricaProduct(item) }), [trackClickProduct], ); const trackItemImpressions = useCallback( (items: AppProduct[]) => { if (items.length === 0) return; trackImpressionsProduct({ products: items.map(toMetricaProduct) }); }, [trackImpressionsProduct], ); return { trackItemPurchase, trackItemView, trackItemClick, trackItemImpressions }; } // Usage in components function ProductList({ products }: { products: AppProduct[] }) { const { trackItemImpressions, trackItemClick } = useAnalytics(); useEffect(() => { trackItemImpressions(products); }, [products.length, trackItemImpressions]); return (
{products.map((product) => (
trackItemClick(product)}> {product.title} - ${product.priceCents / 100}
))}
); } function ProductDetail({ product }: { product: AppProduct }) { const { trackItemView } = useAnalytics(); useEffect(() => { trackItemView(product); }, [product.id, trackItemView]); return
{product.title}
; } ``` -------------------------------- ### Configure Yandex Metrica ID Source: https://github.com/artginzburg/next-ym/blob/main/README.md Set your Yandex Metrica counter ID using the NEXT_PUBLIC_YANDEX_METRICA_ID environment variable. This is the recommended method for configuration. ```env NEXT_PUBLIC_YANDEX_METRICA_ID=12345678 ``` -------------------------------- ### Map domain objects to product format Source: https://github.com/artginzburg/next-ym/blob/main/docs/advanced.md Define a converter function to transform domain-specific item objects into the format expected by Yandex Metrica. ```tsx interface ItemProduct { id: string; title: string; type: 'PREMIUM' | 'BASIC'; category: string; optionCount: number; /** Price in cents as stored in your DB. */ priceCents: number; } function toProduct(item: ItemProduct) { return { id: item.id, name: `${item.type === 'PREMIUM' ? 'Premium' : 'Basic'}: ${item.title}`, price: item.priceCents / 100, // Metrica expects the display currency category: item.category, variant: `${item.optionCount} options`, quantity: 1, }; } ``` -------------------------------- ### Noscript Tracking Pixel Source: https://github.com/artginzburg/next-ym/blob/main/README.md Provides a fallback tracking pixel for users with JavaScript disabled. This ensures basic visit counts are registered in Metrica. ```html ``` -------------------------------- ### JavaScript-disabled Fallback (noscript) Source: https://github.com/artginzburg/next-ym/blob/main/README.md Automatically renders a noscript tracking pixel for users with JavaScript disabled, ensuring basic visit tracking. ```APIDOC ## JavaScript-disabled Fallback (noscript) ### Description `YandexMetricaProvider` renders a `