Skip to content

feat: allow async reroute #13520

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
Mar 4, 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
5 changes: 5 additions & 0 deletions .changeset/cool-donkeys-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: allow async `reroute`
2 changes: 2 additions & 0 deletions documentation/docs/30-advanced/20-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ The `lang` parameter will be correctly derived from the returned pathname.

Using `reroute` will _not_ change the contents of the browser's address bar, or the value of `event.url`.

Since version 2.18, the `reroute` hook can be asynchronous, allowing it to (for example) fetch data from your backend to decide where to reroute to. Use this carefully and make sure it's fast, as it will delay navigation otherwise.

### transport

This is a collection of _transporters_, which allow you to pass custom types — returned from `load` and form actions — across the server/client boundary. Each transporter contains an `encode` function, which encodes values on the server (or returns `false` for anything that isn't an instance of the type) and a corresponding `decode` function:
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,7 @@ export type ClientInit = () => MaybePromise<void>;
* The [`reroute`](https://svelte.dev/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.
* @since 2.3.0
*/
export type Reroute = (event: { url: URL }) => void | string;
export type Reroute = (event: { url: URL }) => MaybePromise<void | string>;

/**
* The [`transport`](https://svelte.dev/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.
Expand Down
12 changes: 6 additions & 6 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -1198,13 +1198,13 @@ async function load_root_error_page({ status, error, url, route }) {
/**
* Resolve the relative rerouted URL for a client-side navigation
* @param {URL} url
* @returns {URL | undefined}
* @returns {Promise<URL | undefined>}
*/
function get_rerouted_url(url) {
// reroute could alter the given URL, so we pass a copy
async function get_rerouted_url(url) {
let rerouted;
try {
rerouted = app.hooks.reroute({ url: new URL(url) }) ?? url;
// reroute could alter the given URL, so we pass a copy
rerouted = (await app.hooks.reroute({ url: new URL(url) })) ?? url;

if (typeof rerouted === 'string') {
const tmp = new URL(url); // do not mutate the incoming URL
Expand Down Expand Up @@ -1246,7 +1246,7 @@ async function get_navigation_intent(url, invalidating) {
if (is_external_url(url, base, app.hash)) return;

if (__SVELTEKIT_CLIENT_ROUTING__) {
const rerouted = get_rerouted_url(url);
const rerouted = await get_rerouted_url(url);
if (!rerouted) return;

const path = get_url_path(rerouted);
Expand Down Expand Up @@ -1997,7 +1997,7 @@ export async function preloadCode(pathname) {
}

if (__SVELTEKIT_CLIENT_ROUTING__) {
const rerouted = get_rerouted_url(url);
const rerouted = await get_rerouted_url(url);
if (!rerouted || !routes.find((route) => route.exec(get_url_path(rerouted)))) {
throw new Error(`'${pathname}' did not match any routes`);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/respond.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export async function respond(request, options, manifest, state) {

try {
// reroute could alter the given URL, so we pass a copy
resolved_path = options.hooks.reroute({ url: new URL(url) }) ?? url.pathname;
resolved_path = (await options.hooks.reroute({ url: new URL(url) })) ?? url.pathname;
} catch {
return text('Internal Server Error', {
status: 500
Expand Down
8 changes: 8 additions & 0 deletions packages/kit/test/apps/basics/src/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ export const reroute = ({ url }) => {
throw new Error('Server Error - Should trigger 500 response');
}

if (url.pathname === '/reroute/async/a') {
return new Promise((resolve) => {
setTimeout(() => {
resolve('/reroute/async/b');
}, 100);
});
}

if (url.pathname in mapping) {
return mapping[url.pathname];
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<a href="/reroute/async/a">Go to url that should be rewritten</a>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Should have been rewritten to <code>/reroute/async/b</code></h1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
import { page } from '$app/state';
</script>

<h1>Successfully rewritten, URL should still show a: {page.url.pathname}</h1>
8 changes: 8 additions & 0 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1217,7 +1217,7 @@
expect(page.locator('p.loadingfail')).toBeHidden();
});

test('Catches fetch errors from server load functions (direct hit)', async ({ page }) => {

Check warning on line 1220 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit (18, ubuntu-latest, chromium)

flaky test: Catches fetch errors from server load functions (direct hit)

retries: 2
page.goto('/streaming/server-error');
await expect(page.locator('p.eager')).toHaveText('eager');
await expect(page.locator('p.fail')).toHaveText('fail');
Expand Down Expand Up @@ -1402,6 +1402,14 @@
);
});

test('Apply async reroute during client side navigation', async ({ page }) => {
await page.goto('/reroute/async');
await page.click("a[href='/reroute/async/a']");
expect(await page.textContent('h1')).toContain(
'Successfully rewritten, URL should still show a: /reroute/async/a'
);
});

test('Apply reroute after client-only redirects', async ({ page }) => {
await page.goto('/reroute/client-only-redirect');
expect(await page.textContent('h1')).toContain('Successfully rewritten');
Expand Down
7 changes: 7 additions & 0 deletions packages/kit/test/apps/basics/test/server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,13 @@ test.describe('reroute', () => {
);
});

test('Apply async reroute when directly accessing a page', async ({ page }) => {
await page.goto('/reroute/async/a');
expect(await page.textContent('h1')).toContain(
'Successfully rewritten, URL should still show a: /reroute/async/a'
);
});

test('Returns a 500 response if reroute throws an error on the server', async ({ page }) => {
const response = await page.goto('/reroute/error-handling/server-error');
expect(response?.status()).toBe(500);
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ declare module '@sveltejs/kit' {
* The [`reroute`](https://svelte.dev/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.
* @since 2.3.0
*/
export type Reroute = (event: { url: URL }) => void | string;
export type Reroute = (event: { url: URL }) => MaybePromise<void | string>;

/**
* The [`transport`](https://svelte.dev/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.
Expand Down
Loading