Skip to content

feat(astro): Implement Request Route Parametrization for Astro 5 #17105

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 6 commits into from
Jul 21, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -245,7 +245,7 @@ test.describe('nested SSR routes (client, server, server request)', () => {

// Server HTTP request transaction - should be parametrized (todo: currently not parametrized)
expect(serverHTTPServerRequestTxn).toMatchObject({
transaction: 'GET /api/user/myUsername123.json', // todo: should be parametrized to 'GET /api/user/[userId].json'
transaction: 'GET /api/user/[userId].json',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: Is there a test that ensures that a known route like GET / api/user/settings.json? Just wanna make sure we can disambiguate these routes :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not yet, but I was thinking about that!

In this case, it would work as user/settings and user/someID can be differentiated easily by matching the routePattern. routePattern will be user/settings or user/[userid] (all lowercased).

transaction_info: { source: 'route' },
contexts: {
trace: {
Expand Down Expand Up @@ -294,7 +294,7 @@ test.describe('nested SSR routes (client, server, server request)', () => {
});

expect(serverPageRequestTxn).toMatchObject({
transaction: 'GET /catchAll/[path]',
transaction: 'GET /catchAll/[...path]',
transaction_info: { source: 'route' },
contexts: {
trace: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ test.describe('tracing in static routes with server islands', () => {
]),
);

expect(baggageMetaTagContent).toContain('sentry-transaction=GET%20%2Fserver-island%2F'); // URL-encoded for 'GET /test-static/'
expect(baggageMetaTagContent).toContain('sentry-transaction=GET%20%2Fserver-island'); // URL-encoded for 'GET /server-island'
expect(baggageMetaTagContent).toContain('sentry-sampled=true');

const serverIslandEndpointTxn = await serverIslandEndpointTxnPromise;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ test.describe('tracing in static/pre-rendered routes', () => {
type: 'transaction',
});

expect(baggageMetaTagContent).toContain('sentry-transaction=GET%20%2Ftest-static%2F'); // URL-encoded for 'GET /test-static/'
expect(baggageMetaTagContent).toContain('sentry-transaction=GET%20%2Ftest-static'); // URL-encoded for 'GET /test-static'
expect(baggageMetaTagContent).toContain('sentry-sampled=true');

await page.waitForTimeout(1000); // wait another sec to ensure no server transaction is sent
Expand Down
59 changes: 56 additions & 3 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { consoleSandbox } from '@sentry/core';
import { readFileSync, writeFileSync } from 'node:fs';
import { consoleSandbox, debug } from '@sentry/core';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import type { AstroConfig, AstroIntegration } from 'astro';
import type { AstroConfig, AstroIntegration, RoutePart } from 'astro';
import * as fs from 'fs';
import * as path from 'path';
import { buildClientSnippet, buildSdkInitFileImportSnippet, buildServerSnippet } from './snippets';
import type { SentryOptions } from './types';
import type { IntegrationResolvedRoute, SentryOptions } from './types';

const PKG_NAME = '@sentry/astro';

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

return {
name: PKG_NAME,
hooks: {
Expand Down Expand Up @@ -134,6 +137,8 @@ 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 @@ -165,6 +170,15 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
});
}
},

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

includeRouteDataToConfigFile(sentryServerInitPath, routes);
},
},
};
};
Expand Down Expand Up @@ -271,3 +285,42 @@ 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('/')}`;
}

function includeRouteDataToConfigFile(sentryInitPath: string, routes: IntegrationResolvedRoute[]): void {
try {
const serverInitContent = readFileSync(sentryInitPath, '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(sentryInitPath, updatedServerInitContent, 'utf8');

debug.log('Successfully added route pattern information to Sentry config file:', sentryInitPath);
} catch (error) {
debug.warn(`Failed to write to Sentry config file at ${sentryInitPath}:`, error);
}
}
21 changes: 21 additions & 0 deletions packages/astro/src/integration/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { SentryVitePluginOptions } from '@sentry/vite-plugin';
import type { InjectedRoute, RouteData } from 'astro';

type SdkInitPaths = {
/**
Expand Down Expand Up @@ -224,3 +225,23 @@ export type SentryOptions = SdkInitPaths &
debug?: boolean;
// eslint-disable-next-line deprecation/deprecation
} & DeprecatedRuntimeOptions;

/**
* Inline type for official `IntegrationResolvedRoute` (only available after Astro v5)
* The type includes more properties, but we only need some of them.
*
* @see https://github.com/withastro/astro/blob/04e60119afee668264a2ff6665c19a32150f4c91/packages/astro/src/types/public/integrations.ts#L287
*/
export type IntegrationResolvedRoute = InjectedRoute & {
patternRegex: RouteData['pattern'];
segments: RouteData['segments'];
};

/**
* Internal type for Astro routes, as we store an additional `patternCaseSensitive` property alongside the
* lowercased parametrized `pattern` of each Astro route.
*/
export type ResolvedRouteWithCasedPattern = IntegrationResolvedRoute & {
patternRegex: string; // RegEx gets stringified
patternCaseSensitive: string;
};
12 changes: 11 additions & 1 deletion packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
withIsolationScope,
} from '@sentry/node';
import type { APIContext, MiddlewareResponseHandler } from 'astro';
import type { ResolvedRouteWithCasedPattern } from '../integration/types';

type MiddlewareOptions = {
/**
Expand Down Expand Up @@ -95,6 +96,9 @@ async function instrumentRequest(
addNonEnumerableProperty(locals, '__sentry_wrapped__', true);
}

const storedBuildTimeRoutes = (globalThis as unknown as { __sentryRouteInfo?: ResolvedRouteWithCasedPattern[] })
?.__sentryRouteInfo;

const isDynamicPageRequest = checkIsDynamicPageRequest(ctx);

const request = ctx.request;
Expand Down Expand Up @@ -128,7 +132,13 @@ async function instrumentRequest(
}

try {
const interpolatedRoute = interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);
const contextWithRoutePattern = ctx as Parameters<MiddlewareResponseHandler>[0] & { routePattern?: string };
const rawRoutePattern = contextWithRoutePattern.routePattern;

const foundRoute = storedBuildTimeRoutes?.find(route => route.pattern === rawRoutePattern);

const interpolatedRoute =
foundRoute?.patternCaseSensitive || interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also just so that I understand correctly: The ctx.routePattern alone is case-insensitive and we use the build time-injected information so that we get the case-sensitive one?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

const source = interpolatedRoute ? 'route' : 'url';
// storing res in a variable instead of directly returning is necessary to
// invoke the catch block if next() throws
Expand Down
Loading