Skip to content

Commit

Permalink
Make sure to handle rejection when prefetching pages (#10579)
Browse files Browse the repository at this point in the history
* Make sure to handle rejection when prefetching pages

* Update comment

* Make sure to show prefetch error in development still
  • Loading branch information
ijjk committed Feb 18, 2020
1 parent c66f2f7 commit db04cc5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
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

0 comments on commit db04cc5

Please sign in to comment.