Skip to content
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

Make sure to handle rejection when prefetching pages #10579

Merged
merged 3 commits into from Feb 18, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/next/client/link.tsx
Expand Up @@ -209,7 +209,15 @@ class Link extends Component<LinkProps> {
if (!this.p || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client)
const [href, asPath] = this.getPaths()
Router.prefetch(href, asPath, options)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
Router.prefetch(href, asPath, options).catch(err => {
if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors
throw err
}
})
prefetched[href] = true
}

Expand Down
9 changes: 9 additions & 0 deletions test/integration/preload-viewport/pages/invalid-prefetch.js
@@ -0,0 +1,9 @@
import Link from 'next/link'

export default () => (
<>
<Link href="/something-invalid-oops">
<a id="invalid-link">I'm broken...</a>
</Link>
</>
)
15 changes: 15 additions & 0 deletions test/integration/preload-viewport/test/index.test.js
Expand Up @@ -163,6 +163,21 @@ describe('Prefetching Links in viewport', () => {
}
})

it('should not have unhandledRejection when failing to prefetch on link', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(`(function() {
window.addEventListener('unhandledrejection', function (err) {
window.hadUnhandledReject = true;
})
window.next.router.push('/invalid-prefetch');
})()`)

expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()

await browser.elementByCss('#invalid-link').moveTo()
expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()
})

it('should not prefetch when prefetch is explicitly set to false', async () => {
const browser = await webdriver(appPort, '/opt-out')

Expand Down