Unverified Commit 78c5be4e authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add support for navigating to external urls (#45388)

Adds support for `router.push('https://google.com')`,
`router.replace('https://google.com')`, and
`redirect('https://google.com')`.

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 61a6065d
......@@ -96,6 +96,10 @@ function findHeadInCache(
return undefined
}
function isExternalURL(url: URL) {
return url.origin !== location.origin
}
/**
* The global router that wraps the application components.
*/
......@@ -180,9 +184,12 @@ function Router({
navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean
) => {
const url = new URL(href, location.origin)
return dispatch({
type: ACTION_NAVIGATE,
url: new URL(href, location.origin),
url,
isExternalUrl: isExternalURL(url),
forceOptimisticNavigation,
navigateType,
cache: {
......@@ -205,6 +212,10 @@ function Router({
}
prefetched.add(href)
const url = new URL(href, location.origin)
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return
}
try {
const routerTree = window.history.state?.tree || initialTree
const serverResponse = await fetchServerResponse(
......@@ -261,7 +272,12 @@ function Router({
useEffect(() => {
// When mpaNavigation flag is set do a hard navigation to the new url.
if (pushRef.mpaNavigation) {
window.location.href = canonicalUrl
const location = window.location
if (pushRef.pendingPush) {
location.assign(canonicalUrl)
} else {
location.replace(canonicalUrl)
}
return
}
......
......@@ -22,11 +22,36 @@ export function navigateReducer(
state: ReadonlyReducerState,
action: NavigateAction
): ReducerState {
const { url, navigateType, cache, mutable, forceOptimisticNavigation } =
action
const {
url,
isExternalUrl,
navigateType,
cache,
mutable,
forceOptimisticNavigation,
} = action
const pendingPush = navigateType === 'push'
if (isExternalUrl) {
return {
// Set href.
canonicalUrl: url.toString(),
pushRef: {
pendingPush,
mpaNavigation: true,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
const { pathname, search } = url
const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
......
......@@ -65,6 +65,7 @@ export interface RefreshAction {
export interface NavigateAction {
type: typeof ACTION_NAVIGATE
url: URL
isExternalUrl: boolean
navigateType: 'push' | 'replace'
forceOptimisticNavigation: boolean
cache: CacheNode
......
......@@ -117,13 +117,15 @@ function prefetch(
router: NextRouter | AppRouterInstance,
href: string,
as: string,
options: PrefetchOptions
options: PrefetchOptions,
isAppRouter: boolean
): void {
if (typeof window === 'undefined') {
return
}
if (!isLocalURL(href)) {
// app-router supports external urls out of the box so it shouldn't short-circuit here as support for e.g. `replace` is added in the app-router.
if (!isAppRouter && !isLocalURL(href)) {
return
}
......@@ -191,7 +193,12 @@ function linkClicked(
// anchors inside an svg have a lowercase nodeName
const isAnchorNodeName = nodeName.toUpperCase() === 'A'
if (isAnchorNodeName && (isModifiedEvent(e) || !isLocalURL(href))) {
if (
isAnchorNodeName &&
(isModifiedEvent(e) ||
// app-router supports external urls out of the box so it shouldn't short-circuit here as support for e.g. `replace` is added in the app-router.
(!isAppRouter && !isLocalURL(href)))
) {
// ignore click for browser’s default behavior
return
}
......@@ -537,7 +544,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
}
// Prefetch the URL.
prefetch(router, href, as, { locale })
prefetch(router, href, as, { locale }, isAppRouter)
}, [
as,
href,
......@@ -546,6 +553,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
prefetchEnabled,
pagesRouter?.locale,
router,
isAppRouter,
])
const childProps: {
......@@ -619,12 +627,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
return
}
prefetch(router, href, as, {
locale,
priority: true,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
bypassPrefetchedCheck: true,
})
prefetch(
router,
href,
as,
{
locale,
priority: true,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
bypassPrefetchedCheck: true,
},
isAppRouter
)
},
onTouchStart(e) {
if (!legacyBehavior && typeof onTouchStartProp === 'function') {
......@@ -647,12 +661,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
return
}
prefetch(router, href, as, {
locale,
priority: true,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
bypassPrefetchedCheck: true,
})
prefetch(
router,
href,
as,
{
locale,
priority: true,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
bypassPrefetchedCheck: true,
},
isAppRouter
)
},
}
......
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="https://example.vercel.sh/" id="external-link">
External Link
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="https://example.vercel.sh/" id="external-link" replace>
External Link
</Link>
</>
)
}
import { redirect } from 'next/navigation'
export default function Page() {
redirect('https://example.vercel.sh/')
return <></>
}
......@@ -639,6 +639,26 @@ createNextDescribe(
await browser.close()
}
})
it('should push to external url', async () => {
const browser = await next.browser('/link-external/push')
expect(await browser.eval('window.history.length')).toBe(2)
await browser.elementByCss('#external-link').click()
expect(await browser.waitForElementByCss('h1').text()).toBe(
'Example Domain'
)
expect(await browser.eval('window.history.length')).toBe(3)
})
it('should replace to external url', async () => {
const browser = await next.browser('/link-external/replace')
expect(await browser.eval('window.history.length')).toBe(2)
await browser.elementByCss('#external-link').click()
expect(await browser.waitForElementByCss('h1').text()).toBe(
'Example Domain'
)
expect(await browser.eval('window.history.length')).toBe(2)
})
})
describe('server components', () => {
......@@ -2502,7 +2522,6 @@ createNextDescribe(
)
})
// TODO-APP: Enable in development
it('should redirect client-side', async () => {
const browser = await next.browser('/redirect/client-side')
await browser
......@@ -2514,6 +2533,13 @@ createNextDescribe(
'Result Page'
)
})
it('should redirect to external url', async () => {
const browser = await next.browser('/redirect/external')
expect(await browser.waitForElementByCss('h1').text()).toBe(
'Example Domain'
)
})
})
describe('next.config.js redirects', () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment