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( ...@@ -96,6 +96,10 @@ function findHeadInCache(
return undefined return undefined
} }
function isExternalURL(url: URL) {
return url.origin !== location.origin
}
/** /**
* The global router that wraps the application components. * The global router that wraps the application components.
*/ */
...@@ -180,9 +184,12 @@ function Router({ ...@@ -180,9 +184,12 @@ function Router({
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
) => { ) => {
const url = new URL(href, location.origin)
return dispatch({ return dispatch({
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
url: new URL(href, location.origin), url,
isExternalUrl: isExternalURL(url),
forceOptimisticNavigation, forceOptimisticNavigation,
navigateType, navigateType,
cache: { cache: {
...@@ -205,6 +212,10 @@ function Router({ ...@@ -205,6 +212,10 @@ function Router({
} }
prefetched.add(href) prefetched.add(href)
const url = new URL(href, location.origin) const url = new URL(href, location.origin)
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return
}
try { try {
const routerTree = window.history.state?.tree || initialTree const routerTree = window.history.state?.tree || initialTree
const serverResponse = await fetchServerResponse( const serverResponse = await fetchServerResponse(
...@@ -261,7 +272,12 @@ function Router({ ...@@ -261,7 +272,12 @@ function Router({
useEffect(() => { useEffect(() => {
// When mpaNavigation flag is set do a hard navigation to the new url. // When mpaNavigation flag is set do a hard navigation to the new url.
if (pushRef.mpaNavigation) { if (pushRef.mpaNavigation) {
window.location.href = canonicalUrl const location = window.location
if (pushRef.pendingPush) {
location.assign(canonicalUrl)
} else {
location.replace(canonicalUrl)
}
return return
} }
......
...@@ -22,11 +22,36 @@ export function navigateReducer( ...@@ -22,11 +22,36 @@ export function navigateReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: NavigateAction action: NavigateAction
): ReducerState { ): ReducerState {
const { url, navigateType, cache, mutable, forceOptimisticNavigation } = const {
action 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 { pathname, search } = url
const href = createHrefFromUrl(url) const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
const isForCurrentTree = const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree) JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
......
...@@ -65,6 +65,7 @@ export interface RefreshAction { ...@@ -65,6 +65,7 @@ export interface RefreshAction {
export interface NavigateAction { export interface NavigateAction {
type: typeof ACTION_NAVIGATE type: typeof ACTION_NAVIGATE
url: URL url: URL
isExternalUrl: boolean
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
cache: CacheNode cache: CacheNode
......
...@@ -117,13 +117,15 @@ function prefetch( ...@@ -117,13 +117,15 @@ function prefetch(
router: NextRouter | AppRouterInstance, router: NextRouter | AppRouterInstance,
href: string, href: string,
as: string, as: string,
options: PrefetchOptions options: PrefetchOptions,
isAppRouter: boolean
): void { ): void {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
return 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 return
} }
...@@ -191,7 +193,12 @@ function linkClicked( ...@@ -191,7 +193,12 @@ function linkClicked(
// anchors inside an svg have a lowercase nodeName // anchors inside an svg have a lowercase nodeName
const isAnchorNodeName = nodeName.toUpperCase() === 'A' 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 // ignore click for browser’s default behavior
return return
} }
...@@ -537,7 +544,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -537,7 +544,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
} }
// Prefetch the URL. // Prefetch the URL.
prefetch(router, href, as, { locale }) prefetch(router, href, as, { locale }, isAppRouter)
}, [ }, [
as, as,
href, href,
...@@ -546,6 +553,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -546,6 +553,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
prefetchEnabled, prefetchEnabled,
pagesRouter?.locale, pagesRouter?.locale,
router, router,
isAppRouter,
]) ])
const childProps: { const childProps: {
...@@ -619,12 +627,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -619,12 +627,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
return return
} }
prefetch(router, href, as, { prefetch(
locale, router,
priority: true, href,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642} as,
bypassPrefetchedCheck: true, {
}) locale,
priority: true,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
bypassPrefetchedCheck: true,
},
isAppRouter
)
}, },
onTouchStart(e) { onTouchStart(e) {
if (!legacyBehavior && typeof onTouchStartProp === 'function') { if (!legacyBehavior && typeof onTouchStartProp === 'function') {
...@@ -647,12 +661,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -647,12 +661,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
return return
} }
prefetch(router, href, as, { prefetch(
locale, router,
priority: true, href,
// @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642} as,
bypassPrefetchedCheck: true, {
}) 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( ...@@ -639,6 +639,26 @@ createNextDescribe(
await browser.close() 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', () => { describe('server components', () => {
...@@ -2502,7 +2522,6 @@ createNextDescribe( ...@@ -2502,7 +2522,6 @@ createNextDescribe(
) )
}) })
// TODO-APP: Enable in development
it('should redirect client-side', async () => { it('should redirect client-side', async () => {
const browser = await next.browser('/redirect/client-side') const browser = await next.browser('/redirect/client-side')
await browser await browser
...@@ -2514,6 +2533,13 @@ createNextDescribe( ...@@ -2514,6 +2533,13 @@ createNextDescribe(
'Result Page' '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', () => { 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