grafana/k6 · error

matching url with regex

Error message

matching url with regex: %w

What it means

Thrown inside the 'metric' page event handler when k6 evaluates your URL regex: it builds the script `pattern + ".test('" + url + "')"` and runs it in the Sobek runtime (browser/metric_event_mapping.go:19). Any failure of that RunString — invalid regex literal, ReferenceError from a non-regex pattern, or a URL containing a quote/backslash that breaks the string literal — is wrapped with this message. The event.tag call is what invokes it, from page.on('metric', e => e.tag({ name, matches: [{ url, method }] })).

Solutions

  1. Pass a complete, slash-delimited JavaScript regex literal string: url: '/api/goods/\\d+'.
  2. Pretest the pattern in the same script: new RegExp(pattern.source ?? pattern) inside try/catch before calling tag.
  3. Keep patterns simple and anchor them to path segments; avoid quoting metacharacters that also break string literals.
  4. Wrap the tag call in try/catch so one bad URL pattern does not abort the iteration's metric emission.

Example fix

// before
page.on('metric', (e) => e.tag({ name: 'goods', matches: [{ url: 'api/goods' }] }));

// after
page.on('metric', (e) => e.tag({ name: 'goods', matches: [{ url: '/api/goods/' }] }));
Defensive patterns

Strategy: try-catch

Validate before calling

const patterns = [{ url: '/api/goods/', method: 'GET' }];
for (const p of patterns) {
  try { new RegExp(p.url.replace(/^\/(.*)\/$/, '$1')); } catch (_) { throw new Error(`invalid url regex: ${p.url}`); }
}
page.on('metric', (e) => e.tag({ name: 'goods', matches: patterns }));

Type guard

function isRegexLiteralString(s) {
  return typeof s === 'string' && s.length > 2 && s.startsWith('/') && s.endsWith('/') && s.lastIndexOf('/') > 0;
}

Try / catch

page.on('metric', (e) => {
  try { e.tag({ name: 'goods', matches }); } catch (err) { if (/matching url with regex/.test(err.message)) { console.warn(`bad regex pattern, skipping tag: ${err.message}`); return; } throw err; }
});

Prevention

When it happens

Trigger: Passing a bare pattern without regex delimiters — e.g. url: 'api/goods' becomes `api/goods.test('...')` (ReferenceError); an invalid literal like '/goods(' (SyntaxError); or a navigated URL that contains an apostrophe or backslash, which terminates/escapes the embedded '...' string and makes the generated script unparseable.

Common situations: Writing url patterns as plain strings because Go-style regex habits (no delimiters) carry over; copying patterns from k6's options.name/http debug shortcuts; testing against URLs with query strings containing encoded quotes.

Related errors


AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18). Data as JSON: /api/errors/43c5977e2b8462c6. Report an issue: GitHub.

Appendix: source

Thrown at internal/js/modules/k6/browser/browser/metric_event_mapping.go:19

package browser

import (
	"fmt"

	"go.k6.io/k6/v2/internal/js/modules/k6/browser/common"
)

// mapMetricEvent to the JS module.
func mapMetricEvent(vu moduleVU, event common.PageEvent) mapping {
	rt := vu.Runtime()
	em := event.Metric

	return mapping{
		"tag": func(urls common.TagMatches) error {
			callback := func(pattern, url string) (bool, error) {
				matched, err := rt.RunString(pattern + `.test('` + url + `')`)
				if err != nil {
					return false, fmt.Errorf("matching url with regex: %w", err)
				}
				return matched.ToBoolean(), nil
			}

			return em.Tag(callback, urls) //nolint:wrapcheck
		},
	}
}

View on GitHub (pinned to 01ffac6f24)