Skip to content

Commit

Permalink
[fix] browser only redirect during load (#2462)
Browse files Browse the repository at this point in the history
  • Loading branch information
baseballyama authored Sep 28, 2021
1 parent 6ba7e1c commit b61acee
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/sharp-moles-hammer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix browser-only redirect during load.
2 changes: 2 additions & 0 deletions packages/kit/src/runtime/client/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,9 +411,11 @@ export class Renderer {
*/
async _get_navigation_result_from_branch({ page, branch }) {
const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
const redirect = filtered.find((f) => f.loaded && f.loaded.redirect);

/** @type {import('./types').NavigationResult} */
const result = {
redirect: redirect && redirect.loaded ? redirect.loaded.redirect : undefined,
state: {
page,
branch,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as assert from 'uvu/assert';

/** @type {import('test').TestMaker} */
export default function (test) {
test('redirect-on-load', '/redirect-on-load', async ({ base, page, js }) => {
if (js) {
assert.equal(page.url(), `${base}/redirect-on-load/redirected`);
assert.equal(await page.textContent('h1'), 'Hazaa!');
} else {
assert.equal(page.url(), `${base}/redirect-on-load`);
}
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<script context="module">
import { browser } from '$app/env';
export async function load() {
if (browser) {
return {
status: 303,
redirect: '/redirect-on-load/redirected'
};
}
return {};
}
</script>

<h1>Woops!</h1>
<p>You shouldn't be here. You should have been directed to /redirect!</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Hazaa!</h1>
13 changes: 12 additions & 1 deletion packages/kit/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,18 @@ function duplicate(test_fn, config, is_build) {

if (start) {
response = await context.pages.js.goto(context.base + start);
await context.pages.js.evaluate(() => window.started);
// Evaluate will throw an exception if the page is navigated away from while the
// script is executing, which may happen during redirect tests. In that case, the
// start event will be fired after the redirect
for (let i = 0; i <= 9; i++) {
try {
await context.pages.js.evaluate(() => window.started);
break;
} catch (e) {
if (i === 9) throw e;
await context.pages.js.waitForNavigation();
}
}
}

await callback({
Expand Down

0 comments on commit b61acee

Please sign in to comment.