Skip to content
Open
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
13 changes: 13 additions & 0 deletions .changeset/witty-wasps-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'astro': patch
---

Improved the error message when a redirect can't be mapped to its destination. For example, the following redirect
will throw a new error because `/category/[categories]/` contains one dynamic segment, while `/category/[categories]/[page]` has two dynamic segments,
and Astro doesn't know how map the parameters:

```js
export default defineConfig({
redirects: { "/category/[categories]": "/category/[categories]/[page]" }
})
```
19 changes: 19 additions & 0 deletions packages/astro/src/core/errors/errors-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,25 @@ export const UnsupportedExternalRedirect = {
hint: 'An external redirect must start with http or https, and must be a valid URL.',
} satisfies ErrorData;

/**
* @docs
* @see
* - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect)
* @description
* A redirect can't be mapped when origin and destination have different segments.
*/
export const RedirectMappingMismatch = {
name: 'RedirectMappingMismatch',
title: "A redirect can't be mapped when origin and destination have different segments",
message: (
fromRoute: string,
toRoute: string,
fromDynamicSegments: number,
toDynamicSegments: number,
) =>
`The number of dynamic segments don't match. The route ${fromRoute} has ${fromDynamicSegments} segments, while ${toRoute} has ${toDynamicSegments} segments.`,
} satisfies ErrorData;

/**
* @docs
* @see
Expand Down
57 changes: 56 additions & 1 deletion packages/astro/src/core/routing/manifest/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { RouteData, RoutePart } from '../../../types/public/internal.js';
import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../constants.js';
import {
MissingIndexForInternationalization,
RedirectMappingMismatch,
UnsupportedExternalRedirect,
} from '../../errors/errors-data.js';
import { AstroError } from '../../errors/index.js';
Expand Down Expand Up @@ -364,6 +365,12 @@ function createRedirectRoutes(
});
}

const redirectRoute = routeMap.get(destination);

if (redirectRoute) {
validateRouteMapping(segments, from, redirectRoute.segments ?? [], redirectRoute.route ?? '');
}

routes.push({
type: 'redirect',
// For backwards compatibility, a redirect is never considered an index route.
Expand All @@ -377,7 +384,7 @@ function createRedirectRoutes(
pathname: pathname || void 0,
prerender: getPrerenderDefault(config),
redirect: to,
redirectRoute: routeMap.get(destination),
redirectRoute,
fallbackRoutes: [],
distURL: [],
origin: 'project',
Expand All @@ -387,6 +394,54 @@ function createRedirectRoutes(
return routes;
}

/**
* Checks whether `a` can be mapped to `b`. If the requirements don't match,
* an error is thrown.
* @param fromSegments
* @param fromRoute
* @param toSegments
* @param toRoute
*/
function validateRouteMapping(
fromSegments: RoutePart[][],
fromRoute: string,
toSegments: RoutePart[][],
toRoute: string,
) {
const fromHasSpread = fromSegments.some((routePart) => routePart.some((part) => part.spread));
const toHasSpread = toSegments.some((routePart) => routePart.some((part) => part.spread));

if (fromHasSpread || toHasSpread) {
return;
}

const fromDynamicSegments = fromSegments.reduce((dynamicSegments, routePart) => {
if (routePart.some((part) => part.dynamic || part.spread)) {
dynamicSegments += 1;
}
return dynamicSegments;
}, 0);

const toDynamicSegments = toSegments.reduce((dynamicSegments, routePart) => {
if (routePart.some((part) => part.dynamic || part.spread)) {
dynamicSegments += 1;
}
return dynamicSegments;
}, 0);

if (fromDynamicSegments != toDynamicSegments) {
throw new AstroError({
...RedirectMappingMismatch,
message: RedirectMappingMismatch.message(
fromRoute,
toRoute,
fromDynamicSegments,
toDynamicSegments,
),
});
}
}

/**
* Checks whether a route segment is static.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---

export function getStaticPaths() {
return [{ params: { category: 'test', slug: 'test' } }]
}

const { slug, category } = Astro.params
---

<p>
{slug} and {category}
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---

export function getStaticPaths() {
return [{ params: { category: 'test' } }]
}
---

<h1>Redirect me!</h1>
22 changes: 22 additions & 0 deletions packages/astro/test/redirects.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -345,4 +345,26 @@ describe('Astro.redirect', () => {
assert.equal(secretHtml.includes('url=/login'), true);
});
});

describe('should fail for redirects that cannot be mapped ', () => {
it('should fail for redirects that cannot be mapped', async () => {
fixture = await loadFixture({
root: './fixtures/redirects/',
output: 'static',
redirects: {
'/old/[category]/1': '/old/[category]/[slug]',
},
});
try {
await fixture.build();
assert.fail('Expected build to fail');
} catch (e) {
assert.equal(
e.message,
"The number of dynamic segments don't match. The route /old/[category]/1 has 1 segments, while /old/[category]/[slug] has 2 segments.",
);
assert.ok(true);
}
});
});
});
Loading