#Tunneling with replays in js

6 messages · Page 1 of 1 (latest)

cursive shell
#

I had a look at tunneling as described here: https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option
I used the example and implemented it in my sveltekit app like that (see below).

import type { RequestHandler } from '@sveltejs/kit';
import { json } from '@sveltejs/kit';
import { PUBLIC_SENTRY_DSN } from '$env/static/public';

const SENTRY_HOST = new URL(PUBLIC_SENTRY_DSN).host;
const SENTRY_PROJECT_IDS = [new URL(PUBLIC_SENTRY_DSN).pathname.replace('/', '')];

export const POST: RequestHandler = async ({ request }) => {
    try {
        const envelopeBytes = await request.arrayBuffer();
        const envelope = new TextDecoder().decode(envelopeBytes);
        const piece = envelope.split('\n')[0];
        const header = JSON.parse(piece);
        const dsn = new URL(header['dsn']);
        const project_id = dsn.pathname?.replace('/', '');

        if (dsn.hostname !== SENTRY_HOST) {
            throw new Error(`Invalid sentry hostname: ${dsn.hostname}`);
        }

        if (!project_id || !SENTRY_PROJECT_IDS.includes(project_id)) {
            throw new Error(`Invalid sentry project id: ${project_id}`);
        }

        const upstream_sentry_url = `https://${SENTRY_HOST}/api/${project_id}/envelope/`;
        await fetch(upstream_sentry_url, {
            method: 'POST',
            body: envelopeBytes
        });

        return json({}, { status: 200 });
    } catch (e) {
        console.error('error tunneling to sentry', e);
        return json({ error: 'error tunneling to sentry' }, { status: 500 });
    }
};

This works fine, but as soon as I enable replays, it fails with an error where it is unable to parse some json.
Is it possible that the example in the docs does not work for replays and needs updating? I would expect

winter plover
cursive shell
#

Interesting! That does seem to avoid the errors. But I have a very hard time triggering replays at all. They now show up fine as issues, but no replays are sent. Even when I disable the tunnel and my ad blocker I can't seem to reliably trigger replays on each click on the example error page!

cursive shell
#
Sentry.init({
    dsn: PUBLIC_SENTRY_DSN,
    tracesSampleRate: Number(PUBLIC_SENTRY_TRACES_SAMPLE_RATE)
});
loadAllLocales();
const L = i18n();

const proxies = handleProxies([
    [
        '/sentry-tunnel',
        {
            to: SENTRY_UPSTREAM_URL,
            requestHook: (event) => {
                const request = event.request.clone();
                request.headers.set('X-Sentry-Auth', `Sentry sentry_key=${SENTRY_KEY}, sentry_version=7`);
                request.headers.set('Content-Type', 'application/x-sentry-envelope');
                return request;
            }
        }
    ]
]);

export const handle: Handle = sequence(
    Sentry.sentryHandle(),
    proxies,
    async ({ event, resolve }) => {
        // read language slug
        const [, lang] = getPathnameWithoutBase(event.url).split('/');

        // redirect to base locale if no locale slug was found
        if (!lang) {
            const locale = getPreferredLocale(event);

            throw redirect(307, `${base}/${locale}`);
        }

        // if slug is not a locale, use base locale (e.g. api endpoints)
        const locale = isLocale(lang) ? (lang as Locales) : getPreferredLocale(event);
        const LL = L[locale];

        // bind locale and translation functions to current request
        event.locals = {
            locale,
            LL
        };

        // replace html lang attribute with correct language
        return resolve(event, { transformPageChunk: ({ html }) => html.replace('%lang%', locale) });
    }
);
const getPreferredLocale = ({ request }: RequestEvent) => {
    // detect the preferred language the user has configured in his browser
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
    const acceptLanguageDetector = initAcceptLanguageHeaderDetector(request);

    return detectLocale(acceptLanguageDetector);
};
export const handleError = Sentry.handleErrorWithSentry();
#

I got this now in my hooks.server.ts but I still am unable to see any replays come through...

winter plover
#

I recommend opening a GH issue in the js sdk repo, the sdk maintainers can help dig in further