remark-add-query-param

remark-add-query-param

A remark plugin to add query parameters to links


Build states npm latest version npm bundle size Visitors count Coverage NPM license follow on twitter

Bug report Β· Feature request



Why? πŸ€”

I use Markdown to write content on my website. I wanted to add query parameters to all the links in blog posts so that I can get insights into the traffic sources as well as help other people who are reading my blog posts to know where the link is coming from. I couldn’t find any existing plugin that does this, so I created one.

So if you have a markdown file like this:

This is a [link](https://example.com)

And you use this plugin with the query parameter utm_source=remark-add-query-param, the output will be:

This is a [link](https://example.com?utm_source=remark-add-query-param)

Usage πŸ’»

First you need to install the package using npm or yarn or pnpm.

npm install remark-add-query-param

Then you can use it in your remark pipeline like this:

import { remark } from 'remark';
import addQueryParam from 'remark-add-query-param';

const processor = remark().use(addQueryParam, {
  externalQueryParams: 'utm_source=remark-add-query-param',
  internalQueryParams: 'source=blog',
});

processor.process('This is a [link](https://example.com)').then((file) => {
  console.log(String(file)); // This is a [link](https://example.com?utm_source=remark-add-query-param)
});

The plugin also supports using multiple query parameters like this:

import { remark } from 'remark';
import addQueryParam from 'remark-add-query-param';

const processor = remark().use(addQueryParam, {
  externalQueryParams: ['utm_source=remark-add-query-param', 'utm_medium=markdown'],
  internalQueryParams: ['source=blog', 'campaign=internal'],
});

processor.process('This is a [link](https://example.com)').then((file) => {
  console.log(String(file)); // This is a [link](https://example.com?utm_source=remark-add-query-param&utm_medium=markdown)
});

You can also add query parameters to only one type of link:

// Only add to external links
const processor = remark().use(addQueryParam, {
  externalQueryParams: 'utm_source=remark-add-query-param',
});

// Only add to internal links  
const processor = remark().use(addQueryParam, {
  internalQueryParams: 'source=blog',
});

Dynamic Parameters πŸš€

You can also use dynamic parameters that are calculated based on the current file being processed. This is perfect for tracking which specific pages are generating traffic:

import { remark } from 'remark';
import addQueryParam from 'remark-add-query-param';

const processor = remark().use(addQueryParam, {
  externalQueryParams: [
    'utm_source=akashrajpurohit.com',
    {
      key: 'utm_medium',
      dynamic: (context) => context.file.stem, // Returns filename without extension
    },
  ],
});

// For a file named "my-first-blog.mdx", this will add:
// utm_source=akashrajpurohit.com&utm_medium=my-first-blog

The dynamic function receives a context object with:

Common VFile properties you can use:

More dynamic parameter examples:

// Track by directory/section
{
  key: 'section',
  dynamic: (context) => context.file.dirname || 'root'
}

// Track target domain for external links
{
  key: 'target_domain',
  dynamic: (context) => {
    try {
      return new URL(context.linkUrl).hostname;
    } catch {
      return 'unknown';
    }
  }
}

// Custom slug generation
{
  key: 'post_id',
  dynamic: (context) => context.file.stem.replace(/-/g, '_')
}

// Date-based tracking (if filename contains date)
{
  key: 'published',
  dynamic: (context) => {
    const match = context.file.basename.match(/^(\d{4}-\d{2}-\d{2})/);
    return match ? match[1] : 'unknown';
  }
}

One of the key advantages of the new API is that you can now specify different query parameters for internal and external links. This is particularly useful for:

This allows you to get more granular analytics and better understand how users navigate through your content vs. where they go when they leave your site.

To ensure the typescript is happy, you can import the types from the package like this:

import type { QueryParam, RemarkAddQueryParamOptions, DynamicQueryParam } from 'remark-add-query-param';

const options: RemarkAddQueryParamOptions = {
  externalQueryParams: 'utm_source=remark-add-query-param' as QueryParam,
  internalQueryParams: 'source=blog' as QueryParam,
};

// Or for multiple query parameters
const options: RemarkAddQueryParamOptions = {
  externalQueryParams: ['utm_source=remark-add-query-param', 'utm_medium=markdown'] as QueryParam[],
  internalQueryParams: ['source=blog', 'campaign=internal'] as QueryParam[],
};

// Or with dynamic parameters
const dynamicOptions: RemarkAddQueryParamOptions = {
  externalQueryParams: [
    'utm_source=akashrajpurohit.com',
    {
      key: 'utm_medium',
      dynamic: (context) => context.file.stem,
    } as DynamicQueryParam,
  ],
};

Integration with Astro

If you are using Astro, you can use this plugin in your astro.config.mjs file like this:

import { defineConfig } from 'astro/config';
import addQueryParam from 'remark-add-query-param';

export default defineConfig({
  markdown: {
    remark: {
      plugins: [
        [
          addQueryParam,
          {
            externalQueryParams: 'utm_source=remark-add-query-param',
            internalQueryParams: 'source=blog',
          },
        ],
      ],
    },
  }
});

Integration with Next.js

If you are using Next.js, you can use this plugin in your next.config.js file like this:

import addQueryParam from 'remark-add-query-param';

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
};

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [
      [
        addQueryParam,
        {
          externalQueryParams: 'utm_source=remark-add-query-param',
          internalQueryParams: 'source=blog',
        },
      ],
    ],
  },
});

export default withMDX(nextConfig);

Configurations βš™οΈ

You can pass the following options to the plugin:

Option Type Description
externalQueryParams QueryParamOrDynamic or QueryParamOrDynamic[] Query parameters to add to external links (HTTP/HTTPS URLs). Can be static strings (key=value) or dynamic objects with functions. Optional.
internalQueryParams QueryParamOrDynamic or QueryParamOrDynamic[] Query parameters to add to internal links (relative URLs). Can be static strings (key=value) or dynamic objects with functions. Optional.

Note: At least one of externalQueryParams or internalQueryParams must be provided.

The plugin will automatically detect the link type and apply the appropriate query parameters.

Migration from v1.x to v2.x πŸš€

Version 2.0.0 introduces a breaking change with a new, more intuitive API. Here’s how to migrate:

Before (v1.x)

// Old API
addQueryParam({
  queryParam: 'utm_source=mywebsite',
  externalLinks: true,
  internalLinks: true,
});

After (v2.x)

// New API - much clearer!
addQueryParam({
  externalQueryParams: 'utm_source=mywebsite',
  internalQueryParams: 'source=blog',
});

Key Changes:

Contributing πŸ«±πŸ»β€πŸ«²πŸΌ

Follow the contribution guidelines to contribute to this project.

Bugs or Requests πŸ›

If you encounter any problems feel free to open an issue. If you feel the project is missing a feature, please raise a ticket on GitHub and I’ll look into it. Pull requests are also welcome.

Where to find me? πŸ‘€

Website Badge Twitter Badge Linkedin Badge Instagram Badge Telegram Badge