New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

astro-ym

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

astro-ym

Yandex Metrika integration for Astro with full ClientRouter support

latest
Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
25
212.5%
Maintainers
1
Weekly downloads
 
Created
Source

astro-ym

npm version License: MIT TypeScript

Lightweight, type-safe Yandex Metrika integration for Astro.

Designed for Astro 4+ and Astro 5+ (supports both View Transitions and the new Client Router). It handles SPA navigation correctly out of the box, eliminating duplicate hits and ensuring accurate tracking.

✨ Features

  • 🚀 Client Router Support: Automatically tracks page views on route changes (SPA navigation) using astro:page-load.
  • 💤 Lazy Loading: Optional lazy load of Yandex Metrika script (load on first user interaction or after timeout) for better Lighthouse scores.
  • Zero Config: Smart defaults (Clickmap, Link tracking enabled by default).
  • 🛡 TypeScript: Fully typed component and helper functions.
  • 🎯 Goals Helper: Exported reachGoal function for easy conversion tracking.
  • 🪶 Lightweight: Uses the modern Yandex tag.js structure and queues calls before the script loads.

📦 Installation

npm install astro-ym

🚀 Usage

Add the <YandexMetrika /> component to your main Layout file (e.g., src/layouts/Layout.astro). It is recommended to place it before the closing </body> tag.

---
import { YandexMetrika } from 'astro-ym';
---

<html lang="en">
  <head>
    <!-- Your meta tags -->
  </head>
  <body>
    <slot />

    <!-- Basic usage -->
    <YandexMetrika counterId={12345678} />
  </body>
</html>

Advanced Configuration

You can enable/disable specific features via props.

<YandexMetrika
  counterId={12345678}
  clickmap={true}
  trackLinks={true}
  accurateTrackBounce={true}
  webvisor={true}
  ecommerce="dataLayer"
  params={{ source: "astro" }}
/>

You can enable lazy loading so that the Yandex Metrika script loads only after the first user interaction (scroll, click, mousemove, touch, keydown) or after a fallback timeout.

<YandexMetrika
  counterId={12345678}
  webvisor={true}
  lazy={true}
  // optional: fallback timeout in ms (default: 3500)
  timeout={4000}
/>

This keeps ym available immediately (calls are queued), but delays loading tag.js to improve performance metrics like TBT and LCP.

🎯 Sending Goals (Conversions)

You can trigger goals from anywhere in your client-side code (UI components, scripts) using the exported helper. It automatically detects the counter ID.

Example in a React/Preact/Solid component:

import { reachGoal } from "astro-ym";

export const BuyButton = () => {
  const handleClick = () => {
    // Send goal
    reachGoal("purchase_click");

    // With params
    // reachGoal('purchase_click', { price: 100, currency: 'USD' });
  };

  return <button onClick={handleClick}>Buy Now</button>;
};

Example in Astro script tag:

<script>
  import { reachGoal } from "astro-ym";

  document.getElementById("my-btn")?.addEventListener("click", () => {
    reachGoal("my_target_id");
  });
</script>

📚 Props Reference

PropTypeDefaultDescription
counterIdnumber | stringRequiredYour Yandex Metrika Counter ID.
ssrbooleantrueHelps Yandex detect initial server-side load correctly.
webvisorbooleanfalseEnables Webvisor (session recording).
clickmapbooleantrueEnables Click map.
trackLinksbooleantrueTracks external link clicks.
accurateTrackBounceboolean | numbertrueAccurate bounce rate tracking (true = 15s, or pass custom timeout in ms).
ecommerceboolean | stringfalseEnable E-commerce data collection. Pass container name (e.g., "dataLayer") if needed.
typenumber0Counter type. 1 for Yandex Advertising Network (RSYA), 0 for standard.
trackHashbooleanfalseTrack changes in the URL hash (#anchor) as separate hits.
sendTitlebooleantrueSend the page <title> with each hit.
childIframebooleanfalseRecord iframe content without a counter.
trustedDomainsstring[]undefinedList of trusted domains for iframe recording.
paramsobject | any[]undefinedVisit parameters (session params).
userParamsobjectundefinedUser parameters.
configRecord<string,any>{}Any additional raw Yandex config. defer and triggerEvent are controlled by the component.
debugbooleanfalseLogs init and hits to console for debugging.
lazybooleanfalseEnable lazy loading of tag.js (loads on first interaction or after timeout).
timeoutnumber3500Fallback timeout (ms) to auto-load script in lazy mode if there is no user interaction.

🛠 Troubleshooting

"Yandex Metrika not initialized" warning

Ensure the <YandexMetrika /> component is mounted on the page. The helper functions (reachGoal) rely on the component being present to access the global counter ID.

AdBlockers

If you don't see events in the dashboard, check if you have an AdBlocker enabled. It often blocks mc.yandex.ru.

Lazy mode enabled but no hits

If you enabled lazy={true} and do not see hits on fast visits, remember that the script loads on first interaction or after the timeout. For critical pages you can disable lazy mode:

<YandexMetrika counterId={12345678} lazy={false} />

Author

Created by KochGO — AI Solutions Architect.

📄 License

MIT © KochGO

Keywords

astro

FAQs

Package last updated on 02 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts