Skip to content

fix(v9/astro): Revert Astro v5 storing route data to globalThis #17185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ test.describe('nested SSR routes (client, server, server request)', () => {

// Server HTTP request transaction
expect(serverHTTPServerRequestTxn).toMatchObject({
transaction: 'GET /api/user/[userId].json',
transaction: 'GET /api/user/myUsername123.json', // fixme: should be GET /api/user/[userId].json
transaction_info: { source: 'route' },
contexts: {
trace: {
Expand Down Expand Up @@ -278,13 +278,13 @@ test.describe('nested SSR routes (client, server, server request)', () => {
await page.goto('/catchAll/hell0/whatever-do');

const routeNameMetaContent = await page.locator('meta[name="sentry-route-name"]').getAttribute('content');
expect(routeNameMetaContent).toBe('%2FcatchAll%2F%5B...path%5D');
expect(routeNameMetaContent).toBe('%2FcatchAll%2F%5Bpath%5D'); // fixme: should be %2FcatchAll%2F%5B...path%5D

const clientPageloadTxn = await clientPageloadTxnPromise;
const serverPageRequestTxn = await serverPageRequestTxnPromise;

expect(clientPageloadTxn).toMatchObject({
transaction: '/catchAll/[...path]',
transaction: '/catchAll/[path]', // fixme: should be /catchAll/[...path]
transaction_info: { source: 'route' },
contexts: {
trace: {
Expand All @@ -300,7 +300,7 @@ test.describe('nested SSR routes (client, server, server request)', () => {
});

expect(serverPageRequestTxn).toMatchObject({
transaction: 'GET /catchAll/[...path]',
transaction: 'GET /catchAll/[path]', // fixme: should be GET /catchAll/[...path]
transaction_info: { source: 'route' },
contexts: {
trace: {
Expand Down
57 changes: 3 additions & 54 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { readFileSync, writeFileSync } from 'node:fs';
import { consoleSandbox, debug } from '@sentry/core';
import { consoleSandbox } from '@sentry/core';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import type { AstroConfig, AstroIntegration, RoutePart } from 'astro';
import type { AstroConfig, AstroIntegration } from 'astro';
import * as fs from 'fs';
import * as path from 'path';
import { buildClientSnippet, buildSdkInitFileImportSnippet, buildServerSnippet } from './snippets';
import type { IntegrationResolvedRoute, SentryOptions } from './types';
import type { SentryOptions } from './types';

const PKG_NAME = '@sentry/astro';

export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
let sentryServerInitPath: string | undefined;
let didSaveRouteData = false;

return {
name: PKG_NAME,
hooks: {
Expand Down Expand Up @@ -138,8 +134,6 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
injectScript('page-ssr', buildServerSnippet(options || {}));
}

sentryServerInitPath = pathToServerInit;

// Prevent Sentry from being externalized for SSR.
// Cloudflare like environments have Node.js APIs are available under `node:` prefix.
// Ref: https://developers.cloudflare.com/workers/runtime-apis/nodejs/
Expand Down Expand Up @@ -171,36 +165,6 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
});
}
},

// @ts-expect-error - This hook is available in Astro 5+
'astro:routes:resolved': ({ routes }: { routes: IntegrationResolvedRoute[] }) => {
if (!sentryServerInitPath || didSaveRouteData) {
return;
}

try {
const serverInitContent = readFileSync(sentryServerInitPath, 'utf8');

const updatedServerInitContent = `${serverInitContent}\nglobalThis["__sentryRouteInfo"] = ${JSON.stringify(
routes.map(route => {
return {
...route,
patternCaseSensitive: joinRouteSegments(route.segments), // Store parametrized routes with correct casing on `globalThis` to be able to use them on the server during runtime
patternRegex: route.patternRegex.source, // using `source` to be able to serialize the regex
};
}),
null,
2,
)};`;

writeFileSync(sentryServerInitPath, updatedServerInitContent, 'utf8');

didSaveRouteData = true; // Prevents writing the file multiple times during runtime
debug.log('Successfully added route pattern information to Sentry config file:', sentryServerInitPath);
} catch (error) {
debug.warn(`Failed to write to Sentry config file at ${sentryServerInitPath}:`, error);
}
},
},
};
};
Expand Down Expand Up @@ -307,18 +271,3 @@ export function getUpdatedSourceMapSettings(

return { previousUserSourceMapSetting, updatedSourceMapSetting };
}

/**
* Join Astro route segments into a case-sensitive single path string.
*
* Astro lowercases the parametrized route. Joining segments manually is recommended to get the correct casing of the routes.
* Recommendation in comment: https://github.com/withastro/astro/issues/13885#issuecomment-2934203029
* Function Reference: https://github.com/joanrieu/astro-typed-links/blob/b3dc12c6fe8d672a2bc2ae2ccc57c8071bbd09fa/package/src/integration.ts#L16
*/
function joinRouteSegments(segments: RoutePart[][]): string {
const parthArray = segments.map(segment =>
segment.map(routePart => (routePart.dynamic ? `[${routePart.content}]` : routePart.content)).join(''),
);

return `/${parthArray.join('/')}`;
}
Loading