-
Notifications
You must be signed in to change notification settings - Fork 29.5k
Allow absolute urls in router and Link #15792
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
29be91e
initial impl
Janpot 7ee5218
update build-output
Janpot ea46341
Merge remote-tracking branch 'upstream/canary' into abs-links
Janpot bdec327
add local url tests
Janpot ef22ef4
more tests
Janpot b771bf4
formatting
Janpot ee821b4
native behavior for non-local url
Janpot aa93552
invalid urls
Janpot 8af5391
udate size imit
Janpot c81d3f3
Merge remote-tracking branch 'upstream/canary' into abs-links
Janpot 87be8fe
Merge remote-tracking branch 'upstream/canary' into abs-links
Janpot 04a3d48
fix basePath
Janpot 08678b5
Merge branch 'canary' into abs-links
kodiakhq[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,6 +11,7 @@ import { | |
loadGetInitialProps, | ||
NextPageContext, | ||
ST, | ||
getLocationOrigin, | ||
} from '../utils' | ||
import { isDynamicRoute } from './utils/is-dynamic' | ||
import { getRouteMatcher } from './utils/route-matcher' | ||
|
@@ -47,7 +48,8 @@ export function hasBasePath(path: string): boolean { | |
} | ||
|
||
export function addBasePath(path: string): string { | ||
return basePath | ||
// we only add the basepath on relative urls | ||
return basePath && path.startsWith('/') | ||
? path === '/' | ||
? normalizePathTrailingSlash(basePath) | ||
: basePath + path | ||
|
@@ -58,6 +60,21 @@ export function delBasePath(path: string): string { | |
return path.slice(basePath.length) || '/' | ||
} | ||
|
||
/** | ||
* Detects whether a given url is routable by the Next.js router (browser only). | ||
*/ | ||
export function isLocalURL(url: string): boolean { | ||
if (url.startsWith('/')) return true | ||
try { | ||
// absolute urls can be local if they are on the same origin | ||
const locationOrigin = getLocationOrigin() | ||
const resolved = new URL(url, locationOrigin) | ||
return resolved.origin === locationOrigin && hasBasePath(resolved.pathname) | ||
} catch (_) { | ||
return false | ||
} | ||
} | ||
|
||
type Url = UrlObject | string | ||
|
||
/** | ||
|
@@ -69,12 +86,16 @@ export function resolveHref(currentPath: string, href: Url): string { | |
const base = new URL(currentPath, 'http://n') | ||
const urlAsString = | ||
typeof href === 'string' ? href : formatWithValidation(href) | ||
const finalUrl = new URL(urlAsString, base) | ||
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname) | ||
// if the origin didn't change, it means we received a relative href | ||
return finalUrl.origin === base.origin | ||
? finalUrl.href.slice(finalUrl.origin.length) | ||
: finalUrl.href | ||
try { | ||
const finalUrl = new URL(urlAsString, base) | ||
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname) | ||
// if the origin didn't change, it means we received a relative href | ||
return finalUrl.origin === base.origin | ||
? finalUrl.href.slice(finalUrl.origin.length) | ||
: finalUrl.href | ||
} catch (_) { | ||
return urlAsString | ||
} | ||
} | ||
|
||
function prepareUrlAs(router: NextRouter, url: Url, as: Url) { | ||
|
@@ -93,9 +114,11 @@ function tryParseRelativeUrl( | |
return parseRelativeUrl(url) | ||
} catch (err) { | ||
if (process.env.NODE_ENV !== 'production') { | ||
throw new Error( | ||
`Invalid href passed to router: ${url} https://err.sh/vercel/next.js/invalid-href-passed` | ||
) | ||
setTimeout(() => { | ||
throw new Error( | ||
`Invalid href passed to router: ${url} https://err.sh/vercel/next.js/invalid-href-passed` | ||
) | ||
}, 0) | ||
} | ||
return null | ||
} | ||
|
@@ -434,6 +457,11 @@ export default class Router implements BaseRouter { | |
as: string, | ||
options: TransitionOptions | ||
): Promise<boolean> { | ||
if (!isLocalURL(url)) { | ||
window.location.href = url | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this work with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes, didn't manage to test mailto handlers in selenium, but it's just treated as an external link |
||
return false | ||
} | ||
|
||
if (!(options as any)._h) { | ||
this.isSsr = false | ||
} | ||
|
27 changes: 20 additions & 7 deletions
27
packages/next/next-server/lib/router/utils/parse-relative-url.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import React from 'react' | ||
import Link from 'next/link' | ||
|
||
export async function getServerSideProps({ query: { port } }) { | ||
if (!port) { | ||
throw new Error('port required') | ||
} | ||
return { props: { port } } | ||
} | ||
|
||
export default function Page({ port }) { | ||
return ( | ||
<> | ||
<Link href={`http://localhost:${port}/docs/something-else`}> | ||
<a id="absolute-link">http://localhost:{port}/docs/something-else</a> | ||
</Link> | ||
</> | ||
) | ||
} |
19 changes: 19 additions & 0 deletions
19
test/integration/basepath/pages/absolute-url-no-basepath.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import React from 'react' | ||
import Link from 'next/link' | ||
|
||
export async function getServerSideProps({ query: { port } }) { | ||
if (!port) { | ||
throw new Error('port required') | ||
} | ||
return { props: { port } } | ||
} | ||
|
||
export default function Page({ port }) { | ||
return ( | ||
<> | ||
<Link href={`http://localhost:${port}/rewrite-no-basepath`}> | ||
<a id="absolute-link">http://localhost:{port}/rewrite-no-basepath</a> | ||
</Link> | ||
</> | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import React from 'react' | ||
import Link from 'next/link' | ||
|
||
export default function Page() { | ||
return ( | ||
<> | ||
<Link href="https://vercel.com/"> | ||
<a id="absolute-link">https://vercel.com/</a> | ||
</Link> | ||
<br /> | ||
<Link href="mailto:idk@idk.com"> | ||
<a id="mailto-link">mailto:idk@idk.com</a> | ||
</Link> | ||
</> | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.