Skip to content

fix(v9/astro): Construct parametrized route during runtime #17227

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 2 commits into from
Jul 30, 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/myUsername123.json', // fixme: should be GET /api/user/[userId].json
transaction: '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%5Bpath%5D'); // fixme: should be %2FcatchAll%2F%5B...path%5D
expect(routeNameMetaContent).toBe('%2FcatchAll%2F%5B...path%5D');

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

expect(clientPageloadTxn).toMatchObject({
transaction: '/catchAll/[path]', // fixme: should be /catchAll/[...path]
transaction: '/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]', // fixme: should be GET /catchAll/[...path]
transaction: 'GET /catchAll/[...path]',
transaction_info: { source: 'route' },
contexts: {
trace: {
Expand Down
36 changes: 29 additions & 7 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import {
startSpan,
withIsolationScope,
} from '@sentry/node';
import type { APIContext, MiddlewareResponseHandler } from 'astro';
import type { ResolvedRouteWithCasedPattern } from '../integration/types';
import type { APIContext, MiddlewareResponseHandler, RoutePart } from 'astro';

type MiddlewareOptions = {
/**
Expand Down Expand Up @@ -96,9 +95,6 @@ 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 @@ -135,10 +131,21 @@ async function instrumentRequest(
// `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);

// @ts-expect-error Implicit any on Symbol.for (This is available in Astro 5)
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const routesFromManifest = ctx?.[Symbol.for('context.routes')]?.manifest?.routes;

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const matchedRouteSegmentsFromManifest = routesFromManifest?.find(
(route: { routeData?: { route?: string } }) => route?.routeData?.route === rawRoutePattern,
)?.routeData?.segments;

const parametrizedRoute =
foundRoute?.patternCaseSensitive || interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);
// Astro v5 - Joining the segments to get the correct casing of the parametrized route
(matchedRouteSegmentsFromManifest && joinRouteSegments(matchedRouteSegmentsFromManifest)) ||
// Fallback (Astro v4 and earlier)
interpolateRouteFromUrlAndParams(ctx.url.pathname, ctx.params);

const source = parametrizedRoute ? 'route' : 'url';
// storing res in a variable instead of directly returning is necessary to
Expand Down Expand Up @@ -365,3 +372,18 @@ function checkIsDynamicPageRequest(context: Parameters<MiddlewareResponseHandler
return false;
}
}

/**
* 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