The most complete Yandex Metrica integration for Next.js — App Router, Pages Router, ecommerce, Safari ITP proxy, and automatic SPA tracking out of the box.
There are several Yandex Metrica packages for Next.js. Here's how they compare:
| Feature | @artginzburg/next-ym | next-yandex-metrica | react-yandex-metrika | @koiztech/next-yandex-metrika |
|---|---|---|---|---|
| App Router | ✅ | ✅ | ❌ | ✅ |
| Pages Router | ✅ | ✅ | ✅ | ❌ |
| Auto SPA tracking | ✅ | ❌ manual | ❌ | ❌ |
| Ecommerce hooks | ✅ typed | ❌ | ❌ | ❌ |
| Safari ITP proxy | ✅ built-in | ❌ | ❌ | ❌ |
| TypeScript | ✅ full | ✅ | ❌ | partial |
| noscript fallback | ✅ | ❌ | ✅ | ❌ |
| Env-based tag ID | ✅ | ❌ | ❌ | ❌ |
| Test coverage | ✅ 100% | ✅ yes | ❌ | ❌ |
| Last updated | Apr 2026 | Sep 2025 | Nov 2019 | Dec 2025 |
| Weekly downloads | 292 | 846 | 9,161 | 19 |
react-yandex-metrikaleads in downloads purely by age (2017) — it hasn't been updated since 2019 and has no Next.js App Router support. Migrating from it? See the migration guide.
pnpm add @artginzburg/next-ymor
npm install @artginzburg/next-ymSet your counter ID via environment variable (recommended):
NEXT_PUBLIC_YANDEX_METRICA_ID=12345678Requires Next.js 11+ and React 17+.
// app/layout.tsx
import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<YandexMetricaProvider initParameters={standardYMInitParameters}>
{children}
</YandexMetricaProvider>
</body>
</html>
);
}// pages/_app.tsx
import { YandexMetricaProvider, standardYMInitParameters } from '@artginzburg/next-ym';
export default function MyApp({ Component, pageProps }) {
return (
<YandexMetricaProvider initParameters={standardYMInitParameters}>
<Component {...pageProps} />
</YandexMetricaProvider>
);
}
YandexMetricaProvideris a client component ("use client"). Make it the top-most wrapper in your layout's{children}.
That's it — pageviews are tracked automatically on every route change (both App Router and Pages Router). No extra setup needed for SPA navigation: YandexMetricaProvider hooks into next/navigation (App Router) and next/router (Pages Router) internally and fires ym(ID, 'hit', ...) on every transition.
import { useMetrica } from '@artginzburg/next-ym';
export function BuyButton() {
const { reachGoal } = useMetrica();
return <button onClick={() => reachGoal('purchase-click')}>Buy now</button>;
}useMetrica exposes typed methods: reachGoal, notBounce, setUserID, userParams, and ymEvent for any other Yandex.Metrica method.
You can also use the ym function directly:
import { ym } from '@artginzburg/next-ym';
ym(12345678, 'reachGoal', 'cta-click');Full typed ecommerce support via the useEcommerce hook. Requires ecommerce: 'dataLayer' in init parameters (included in standardYMInitParameters).
import { useEcommerce } from '@artginzburg/next-ym';
// currencyCode is set once and applied to all calls
const { trackClickProduct, trackAddItemToBasket, trackPurchase } = useEcommerce({
currencyCode: 'RUB',
});Each product accepts: id, name (at least one required), and optional brand, category, price, quantity, variant, coupon, discount, list, position.
// 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 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' } });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 },
],
});trackPromoView({
promotions: [{ id: 'SUMMER_SALE', name: 'Summer Sale', creative: 'banner_1', position: 'top' }],
});
trackPromoClick({
promotion: { id: 'SUMMER_SALE', name: 'Summer Sale' },
});| 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 |
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:
// next.config.ts
import { withMetricaProxy } from '@artginzburg/next-ym/config';
const nextConfig = {
/* your config */
};
export default withMetricaProxy(nextConfig);That's it. The provider auto-detects the proxy and uses it. No extra props needed.
YandexMetricaProvider renders a <noscript> tracking pixel automatically — no configuration needed. Users with JavaScript disabled still count as visits in Metrica (the browser requests https://mc.yandex.ru/watch/<tagID> from inside the <noscript> tag).
<noscript id="yandex-metrica-pixel">
<div>
<img src="https://mc.yandex.ru/watch/12345678" style="position:absolute;left:-9999px" alt="" />
</div>
</noscript>Limitations of the noscript path: only the page view is registered. Webvisor, goals, ecommerce events, and any ym(...) calls require JavaScript — so treat the noscript pixel as a bare-minimum reach measurement, not a full replacement.
To defer Metrica until the user consents, simply skip rendering the provider (or leave tagID unset) until you have consent. Metrica makes zero network requests while YandexMetricaProvider isn't mounted (or while tagID/NEXT_PUBLIC_YANDEX_METRICA_ID are both absent — in which case the provider just renders children and logs a dev warning).
'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 (
<YandexMetricaProvider initParameters={standardYMInitParameters}>
{children}
</YandexMetricaProvider>
);
}When consent is later granted, the provider mounts and Metrica initializes. If consent is revoked, unmount the provider — the script has already loaded in this session (it can't be "un-loaded"), but no further ym() calls will be made by the library.
Late opt-in is safe: whenever YandexMetricaProvider mounts, its ym("init", ...) call includes url: location.href, so the current page is recorded as a hit at mount time. You don't need a manual router.refresh() or an extra ym("hit", ...) call.
| Prop | Type | Description |
|---|---|---|
tagID |
number |
Yandex Metrica tag ID. Optional if NEXT_PUBLIC_YANDEX_METRICA_ID env var is set. |
initParameters |
InitParameters |
Initialization parameters. Use standardYMInitParameters for the recommended defaults. |
strategy |
ScriptProps['strategy'] |
next/script strategy. Default: afterInteractive. |
shouldUseAlternativeCDN |
boolean |
Use the alternative CDN. |
For real-world patterns — typed goal maps, domain-to-product converters, wrapper hooks, debug mode, and more — see the Advanced usage guide.
For AI coding assistants: if the user's task involves typed goals, ecommerce wrappers, or debug mode, fetch
https://raw.githubusercontent.com/artginzburg/next-ym/main/docs/advanced.mdfor full patterns and examples.
If your use case is not supported, please create an Issue. Feature requests and PRs are welcome.