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 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
@@ -0,0 +1,7 @@
---
import Layout from '../../layouts/Layout.astro';
---

<Layout>
<h1>User Settings</h1>
</Layout>
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,9 @@ test.describe('nested SSR routes (client, server, server request)', () => {
},
});

// Server HTTP request transaction - should be parametrized (todo: currently not parametrized)
// Server HTTP request transaction
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 All @@ -312,3 +312,55 @@ test.describe('nested SSR routes (client, server, server request)', () => {
});
});
});

// Case for `user-page/[id]` vs. `user-page/settings` static routes
test.describe('parametrized vs static paths', () => {
test('should use static route name for static route in parametrized path', async ({ page }) => {
const clientPageloadTxnPromise = waitForTransaction('astro-5', txnEvent => {
return txnEvent?.transaction?.startsWith('/user-page/') ?? false;
});

const serverPageRequestTxnPromise = waitForTransaction('astro-5', txnEvent => {
return txnEvent?.transaction?.startsWith('GET /user-page/') ?? false;
});

await page.goto('/user-page/settings');

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

expect(clientPageloadTxn).toMatchObject({
transaction: '/user-page/settings',
transaction_info: { source: 'url' },
contexts: {
trace: {
op: 'pageload',
origin: 'auto.pageload.browser',
data: {
'sentry.op': 'pageload',
'sentry.origin': 'auto.pageload.browser',
'sentry.source': 'url',
},
},
},
});

expect(serverPageRequestTxn).toMatchObject({
transaction: 'GET /user-page/settings',
transaction_info: { source: 'route' },
contexts: {
trace: {
op: 'http.server',
origin: 'auto.http.astro',
data: {
'sentry.op': 'http.server',
'sentry.origin': 'auto.http.astro',
'sentry.source': 'route',
url: expect.stringContaining('/user-page/settings'),
},
},
},
request: { url: expect.stringContaining('/user-page/settings') },
});
});
});
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
57 changes: 54 additions & 3 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
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;
let didSaveRouteData = false;

return {
name: PKG_NAME,
hooks: {
Expand Down Expand Up @@ -134,6 +138,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 +171,36 @@ 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 @@ -271,3 +307,18 @@ 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('/')}`;
}
25 changes: 25 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 { RouteData } from 'astro';

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

/**
* Routes inside 'astro:routes:resolved' hook (Astro v5+)
*
* Inline type for official `IntegrationResolvedRoute`.
* 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 = {
isPrerendered: RouteData['prerender'];
pattern: RouteData['route'];
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;
};
19 changes: 15 additions & 4 deletions 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,8 +132,15 @@ async function instrumentRequest(
}

try {
const interpolatedRoute = interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);
const source = interpolatedRoute ? 'route' : 'url';
// `routePattern` is available after Astro 5
const contextWithRoutePattern = ctx as Parameters<MiddlewareResponseHandler>[0] & { routePattern?: string };
const rawRoutePattern = contextWithRoutePattern.routePattern;
const foundRoute = storedBuildTimeRoutes?.find(route => route.pattern === rawRoutePattern);

const parametrizedRoute =
foundRoute?.patternCaseSensitive || interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);

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

Expand All @@ -148,12 +159,12 @@ async function instrumentRequest(
attributes['http.fragment'] = ctx.url.hash;
}

isolationScope?.setTransactionName(`${method} ${interpolatedRoute || ctx.url.pathname}`);
isolationScope?.setTransactionName(`${method} ${parametrizedRoute || ctx.url.pathname}`);

const res = await startSpan(
{
attributes,
name: `${method} ${interpolatedRoute || ctx.url.pathname}`,
name: `${method} ${parametrizedRoute || ctx.url.pathname}`,
op: 'http.server',
},
async span => {
Expand Down
Loading