npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@humandone/utm-params

v1.1.1

Published

Сохраняет query параметры и utm_ метки в cookies. Создает ссылки с параметрами.

Readme

External Links Query Params

Описание

Инструментарий для работы с cookies и UTM метками. Обычно применяются для сохранения UTM меток из GET запроса к странице в cookies и подставления потом их в во внешние ссылки с лендинга на карточки курсов.

Состав

Состоит из базового набора работы cookies:

  • setCookie - установить cookie,
  • getCookie - получить cookie,
  • eraseCookie - удалить,
  • getCookiesMap - получить маппинг всех cookies

Как это работает

При заходе посетителя на сайт UTM метки сохраняются в cookies. При формировании ссылок курсов эти метки парсятся и подставляются в query для дальнейшего анализа статистики аналитиками заказчика.

Как сохранить UTM метки

В зависимости от проекта, есть следующие варианты.

Работа пакета начинается с записи всех UTM меток из GET запроса к приложению в куки. В корне приложения, компоненте, который рендерится всегда (в next.js (SSR) это _document или _app, в CRA(CSR) это какой-нибудь index.js), должна быть вызвана функция saveUtmToCookies, в которую нужно передать предварительно распарсенный при помощи getCookiesMap объект cookies.

Для create-react-app приложения можно реализовать провайдер, пример ниже:

App.js

import React from 'react';
import { BrowserRouter as Router, withRouter } from 'react-router-dom';
import './sass/styles.scss';
import { RoutesContainer } from './router';
import { UTMTracker } from './components/UTMTracker';

function App({ history }) {
    return (
        <div className="App">
        <Router>
            <UTMTracker>
            <RoutesContainer history={history} />
            </UTMTracker>
        </Router>
        </div>
    );
}

UTMTracker провайдер

import React from 'react';
import { saveUTM } from '../utils';

export const UTMTracker = ({ children }) => {
React.useEffect(() => {
    saveUTM();
}, []);
    return <div>{children}</div>;
};

saveUTM

import * as queryString from 'querystring';
import { saveUtmToCookies } from '@humandone/utm-params';

export const saveUTM = () => {
    const parsed = queryString.parse(window.location.search.replace('?', ''));
    if (Object.keys(parsed).length) saveUtmToCookies({ params: parsed });
};

Для Next.js

В корневом компоненте нужно просто обернуть в хук

useEffect(() => {
    saveUTM();
}, []);

Где метод saveUTM точно такой же, как в предыдущем примере

Как добавить UTM метки к внешним ссылкам

Теперь, когда метки сохранены, нужно их добавить к ссылкам курсов. Подходы для CRA приложения и Next.js отличаются, так как в Next.js применяется Server Side Rendering, и, на момент рендера, у интерпретатора нет доступа к объекту document, window и другим, касающимся клиентской стороны, так что cookies он получает через response, прокинутыми с помощью getServerSideProps. Ниже описан метод получения этой ссылки

import {
    buildUrl as buildUrlWithUtmParams,
    getCookiesMap
} from '@humandone/utm-params';

export function buildCourseUrl({
    slug,
    cookies, // <- эти cookies в метод могут приходить как с document, так и с getServerSideProps
}) {
    const cookiesMap = getCookiesMap(cookies);
    const utmCookiesMap = {};

    // Здесь получаем все куки с приставкой utm_
    for (let key in cookiesMap) {
        if (key.includes('utm_')) {
        utmCookiesMap[key] = cookiesMap[key];
        }
    }

    const host = `https://skillbox.com.ua`;
    let url = host;
    url += `${slug}`;

    // Вызываем метод из библиотеки, который собирает нам полный href курса
    return buildUrlWithUtmParams({
        url: url,
        params: utmCookiesMap,
    }).replace(host, '');
}