Skip to content

Commit d0343fa

Browse files
feat(experimental): normalize string locations with new URL (#2932)
* feat(experimental): normalize string locations with new URL * test: cleanup * refactor(experimental): build parsed location from URL * fix(experimental): write query spaces as + in string locations new URL() writes a space in the query as %20 while stringifyQuery() writes +, so '/s?q=a b' and { query: { q: 'a b' } } gave different fullPaths for the same query. Also update the note about + in the query: it follows application/x-www-form-urlencoded like URLSearchParams (#561). * fix(query): encode ' as %27 new URL() encodes ' in the query of special schemes (special-query percent-encode set) and so does URLSearchParams, but encodeQueryValue() kept it. String and object locations now give the same query. Decoded query values do not change. * fix(experimental): encode \ in string location query and hash new URL() keeps a raw \ in the query and hash, but it is not a valid URL code point and stringifyQuery() and encodeHash() write %5C. String locations now write %5C too. * docs(experimental): add URL encoding page Explain how each part of a location is encoded, with collapsed notes on the choices: normalized string locations, + for spaces in the query, and the hash that is never decoded. * docs: encoding in hash * docs(encoding): use generated route names and query arrays <!-- coderabbit-ai-generated:v1 --> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent b5c8151 commit d0343fa

9 files changed

Lines changed: 328 additions & 34 deletions

File tree

‎packages/docs/.vitepress/config/en.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,10 @@ function sidebarFileBasedRouting(): SidebarGroup {
236236
text: 'Vapor Mode (experimental)',
237237
link: '/experimental/vapor',
238238
},
239+
{
240+
text: 'URL Encoding (experimental)',
241+
link: '/experimental/encoding',
242+
},
239243
],
240244
}
241245
}
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# URL Encoding
2+
3+
::: warning Experimental
4+
This page describes the [Experimental Router](./router-resolver.md). The behavior may change.
5+
:::
6+
7+
The router encodes and decodes URLs for you. The rule to remember: **give decoded values** (`params`, `query`) and **read decoded values** (`route.params`, `route.query`). A `path` in an object location must already be encoded. String locations and the `hash` are only normalized: the router encodes the characters that need it and keeps the existing percent encoded sequences.
8+
9+
[[toc]]
10+
11+
## Summary
12+
13+
| Part of the location | You give | The router gives in `route` |
14+
| -------------------- | -------------- | --------------------------- |
15+
| String location | encoded or not | normalized `fullPath` |
16+
| Object `path` | encoded | the same `path` |
17+
| `params` | decoded | decoded `params` |
18+
| `query` values | decoded | decoded `query` |
19+
| `hash` | encoded or not | normalized `hash` |
20+
21+
## Named locations and params
22+
23+
The examples below use the default names generated from the page files. The router encodes each param. In a regular path param, a `/` becomes `%2F`, so the param stays one segment:
24+
25+
```ts
26+
// user/[username].vue
27+
router.push({
28+
name: '/user/[username]',
29+
params: { username: 'eduardo/san martin' },
30+
})
31+
// /user/eduardo%2Fsan%20martin
32+
// route.params.username === 'eduardo/san martin'
33+
```
34+
35+
Two kinds of path params keep a `/` as a separator:
36+
37+
```ts
38+
// repeatable param, articles/[slugs]+.vue: each value is one segment
39+
router.push({ name: '/articles/[slugs]+', params: { slugs: ['a/b', 'c d'] } })
40+
// /articles/a%2Fb/c%20d
41+
42+
// catch-all param, docs/[...path].vue: the value can span segments
43+
router.push({ name: '/docs/[...path]', params: { path: 'guide/intro?' } })
44+
// /docs/guide/intro%3F
45+
```
46+
47+
In all cases, `route.params` has the decoded values. This is the safest form of location. Use it when possible.
48+
49+
## String locations
50+
51+
The router normalizes a string location like a browser does with [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL). It encodes the characters that need it, keeps percent encoded sequences, and resolves `.` and `..` segments:
52+
53+
```ts
54+
router.push('/user/café') // /user/caf%C3%A9
55+
router.push('/user/caf%C3%A9') // same location
56+
router.push('/docs/./guide/../api') // /docs/api
57+
```
58+
59+
::: details Why are string locations normalized but object paths are not?
60+
61+
A string location often comes from outside the app: a link in some content, a URL that a user wrote, or `route.fullPath`. Normalizing it makes it safe to use as is. `new URL()` is slow compared to the other forms, so the router does not use it for an object `path`. Do not build a `path` from dynamic values. Use a named location and let the router encode the params:
62+
63+
```ts
64+
router.push({ name: '/user/[username]', params: { username } }) // [!code ++]
65+
router.push({ path: `/user/${username}` }) // [!code --]
66+
```
67+
68+
:::
69+
70+
## Query
71+
72+
Give decoded query values. The router encodes them, and it decodes them again in `route.query`:
73+
74+
```ts
75+
router.push({ path: '/search', query: { q: ['a&b=c'] } })
76+
// /search?q=a%26b=c
77+
// route.query.q → ['a&b=c']
78+
```
79+
80+
Do not encode query values yourself. The router encodes them a second time:
81+
82+
```ts
83+
router.push({ path: '/search', query: { q: ['a b'] } }) // [!code ++]
84+
router.push({ path: '/search', query: { q: ['a%20b'] } }) // [!code --]
85+
// /search?q=a%2520b, route.query.q → ['a%20b']
86+
```
87+
88+
### Spaces and `+`
89+
90+
In the query, the router writes a space as `+` and a `+` as `%2B`. When it reads a URL, `+` becomes a space. For spaces, all forms of a location give the same URL:
91+
92+
```ts
93+
router.push({ path: '/search', query: { q: ['a b'] } }) // /search?q=a+b
94+
router.push('/search?q=a b') // /search?q=a+b
95+
router.push('/search?q=a%20b') // /search?q=a+b
96+
router.push('/search?q=a+b') // /search?q=a+b
97+
// route.query.q → ['a b'] for all of them
98+
```
99+
100+
To get a literal `+` from a string location, write `%2B`. In a query object, write `+`:
101+
102+
```ts
103+
router.push('/search?q=c%2B%2B') // route.query.q → ['c++']
104+
router.push({ path: '/search', query: { q: ['c++'] } }) // /search?q=c%2B%2B
105+
```
106+
107+
::: details Why `+` and not `%20`?
108+
109+
`new URL()` writes a space in the query as `%20`, but `URLSearchParams`, HTML forms, and search engines write `+`. For example, when you use a website as a search engine in Chrome's address bar, Chrome creates links like `/search?q=a+b` ([#561](https://github.com/vuejs/router/issues/561)). The router reads `+` as a space, like `URLSearchParams`, so these links work.
110+
111+
The router also always writes `+`, so a space in a query value always gives the same URL, whatever the form of the location. Pushing `route.fullPath` again does not change it. The router prefers this consistency over the exact output of `new URL()`.
112+
113+
This applies only to the query. In the path and the hash, a `+` is a `+` and a space is `%20`.
114+
115+
:::
116+
117+
## Hash
118+
119+
The hash is not a decoded value. The router normalizes it like setting [`url.hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash): it encodes the characters that need it and keeps every `%` as it is. `route.hash` is never decoded:
120+
121+
```ts
122+
router.push({ path: '/docs', hash: '#a b' }) // /docs#a%20b
123+
router.push({ path: '/docs', hash: '#a%20b' }) // same location
124+
// route.hash → '#a%20b'
125+
router.push({ path: '/docs', hash: '#100%' }) // /docs#100%
126+
```
127+
128+
Because a `%` is never encoded, `#%20` always means a space. To put the literal text `%20` in a hash, encode the `%` yourself as `%25`:
129+
130+
```ts
131+
router.push({ path: '/docs', hash: '#%2520' }) // /docs#%2520
132+
// route.hash → '#%2520'
133+
decodeURIComponent(route.hash) // '#%20'
134+
```
135+
136+
::: details Why is `route.hash` not decoded?
137+
138+
`route.hash` is the same as [`location.hash`](https://developer.mozilla.org/en-US/docs/Web/API/Location/hash). Decoding it can lose information when the hash has its own structure, for example an OAuth response like `#token=a%26b&state=c`. Use `decodeURIComponent()` if you need the decoded value. It throws on a lone `%` like `#100%`.
139+
140+
:::

‎packages/docs/experimental/router-resolver.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,21 @@ router.push({ name: route.name, params: route.params, query: { page: ['2'] } })
108108
// /search?page=2
109109
```
110110

111+
### Encoding
112+
113+
The router normalizes a string location like a browser does with [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL), so you do not need to encode it yourself. An object location is not normalized: its `path` must already be encoded. Its `query` values and `params` stay decoded because the router encodes them:
114+
115+
```ts
116+
router.push('/café?q=a b') // /caf%C3%A9?q=a+b
117+
router.push({ path: '/caf%C3%A9' }) // [!code ++]
118+
router.push({ path: '/café' }) // [!code --]
119+
router.push({ path: '/search', query: { q: 'a&b' } }) // /search?q=a%26b
120+
router.push({ name: 'user', params: { username: 'eduardo/san martin' } })
121+
// /user/eduardo%2Fsan%20martin
122+
```
123+
124+
See [URL Encoding](./encoding.md) for all the rules, including spaces and `+` in the query.
125+
111126
### Navigation guard redirects
112127

113128
Relative redirects returned by navigation guards use the **target route (`to`)** as their base. This also applies to initial navigation and back/forward navigation:

‎packages/router/__tests__/encoding.spec.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,10 @@ describe('Encoding', () => {
6161
})
6262

6363
describe('query params', () => {
64-
const safePerSpec = "!$'*,:;@[]_|?/{}^()`"
65-
const toEncodeForKey = '"<>#&='
66-
const toEncodeForValue = '"<>#&'
64+
const safePerSpec = '!$*,:;@[]_|?/{}^()`'
65+
// ' is in the special-query percent-encode set, like new URL()
66+
const toEncodeForKey = `"<>#&='`
67+
const toEncodeForValue = `"<>#&'`
6768
const encodedToEncodeForKey = toEncodeForKey
6869
.split('')
6970
.map(c => {

‎packages/router/src/encoding.ts‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,19 @@ import { diagnostics } from './diagnostics'
33
/**
44
* Encoding Rules (␣ = Space)
55
* - Path: ␣ " < > # ? { }
6-
* - Query: ␣ " < > # & =
6+
* - Query: ␣ " < > # & = ' (`'` like the special-query set of new URL())
77
* - Hash: ␣ " < > `
88
*
99
* On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
1010
* defines some extra characters to be encoded. Most browsers do not encode them
1111
* in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
1212
* also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`)
1313
* plus `-._~`. This extra safety should be applied to query by patching the
14-
* string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
15-
* should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
16-
* into a `/` if directly typed in. The _backtick_ (`````) should also be
14+
* string returned by encodeURIComponent encodeURI also encodes `[\]^`.
15+
*
16+
* `\` is always encoded. In the path, browsers transform a `\` into a `/`.
17+
* In the query and hash, `new URL()` keeps it but it is not a valid URL code
18+
* point, so `%5C` keeps the URL valid. The _backtick_ (`````) should also be
1719
* encoded everywhere because some browsers like FF encode it when directly
1820
* written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
1921
*/
@@ -31,15 +33,14 @@ export const SLASH_RE = /\//g // %2F
3133
const EQUAL_RE = /=/g // %3D
3234
const IM_RE = /\?/g // %3F
3335
export const PLUS_RE = /\+/g // %2B
36+
const APOSTROPHE_RE = /'/g // %27
37+
export const BACKSLASH_RE = /\\/g // %5C
3438
/**
35-
* NOTE: It's not clear to me if we should encode the + symbol in queries, it
36-
* seems to be less flexible than not doing so and I can't find out the legacy
37-
* systems requiring this for regular requests like text/html. In the standard,
38-
* the encoding of the plus character is only mentioned for
39-
* application/x-www-form-urlencoded
40-
* (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
41-
* leave the plus character as is in queries. To be more flexible, we allow the
42-
* plus character on the query, but it can also be manually encoded by the user.
39+
* NOTE: queries follow application/x-www-form-urlencoded, like
40+
* `URLSearchParams`: a space is encoded as `+`, a `+` as `%2B`, and
41+
* `parseQuery()` decodes `+` as a space. Search engines (e.g. Chrome's omnibox)
42+
* create links with `+` for spaces (#561). Always writing `+` keeps the
43+
* encoding consistent and idempotent, even if `new URL()` writes `%20`.
4344
*
4445
* Resources:
4546
* - https://url.spec.whatwg.org/#urlencoded-parsing
@@ -53,7 +54,7 @@ const ENC_BACKTICK_RE = /%60/g // `
5354
const ENC_CURLY_OPEN_RE = /%7B/g // {
5455
const ENC_PIPE_RE = /%7C/g // |
5556
const ENC_CURLY_CLOSE_RE = /%7D/g // }
56-
const ENC_SPACE_RE = /%20/g // }
57+
export const ENC_SPACE_RE = /%20/g // space
5758

5859
/**
5960
* Encode characters that need to be encoded on the path, search and hash
@@ -105,6 +106,7 @@ export function encodeQueryValue(text: string | number): string {
105106
.replace(ENC_SPACE_RE, '+')
106107
.replace(HASH_RE, '%23')
107108
.replace(AMPERSAND_RE, '%26')
109+
.replace(APOSTROPHE_RE, '%27')
108110
.replace(ENC_BACKTICK_RE, '`')
109111
.replace(ENC_CURLY_OPEN_RE, '{')
110112
.replace(ENC_CURLY_CLOSE_RE, '}')

‎packages/router/src/experimental/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ export { NavigationResult as _NavigationResult } from './data-loaders/entries/in
169169
*/
170170
export {
171171
experimental_parseURL as _parseURL,
172+
parseEncodedURL as _parseEncodedURL,
172173
experimental_stringifyURL as _stringifyURL,
173174
} from './location'
174175
export {

‎packages/router/src/experimental/location.spec.ts‎

Lines changed: 62 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { experimental_parseQuery as parseQuery } from './query'
22
import {
33
experimental_parseURL as originalParseURL,
4+
parseEncodedURL,
45
experimental_stringifyURL as stringifyURL,
56
} from './location'
67
import { stringifyQuery } from '../query'
7-
import { vi, describe, expect, it } from 'vitest'
8+
import { describe, expect, it } from 'vitest'
89

910
describe('parseURL', () => {
1011
let parseURL = originalParseURL.bind(null, parseQuery)
@@ -248,24 +249,62 @@ describe('parseURL', () => {
248249
})
249250
})
250251

251-
it('calls parseQuery', () => {
252-
const parseQuery = vi.fn()
253-
originalParseURL(parseQuery, '/?é=é&é=a')
254-
expect(parseQuery).toHaveBeenCalledTimes(1)
255-
expect(parseQuery).toHaveBeenCalledWith('é=é&é=a')
252+
describe('normalization like new URL()', () => {
253+
it('encodes characters like a browser', () => {
254+
expect(parseURL('/café b?q=a b#h b')).toEqual({
255+
// spaces in the query are `+` like stringifyQuery()
256+
fullPath: '/caf%C3%A9%20b?q=a+b#h%20b',
257+
path: '/caf%C3%A9%20b',
258+
hash: '#h%20b',
259+
query: { q: ['a b'] },
260+
})
261+
})
262+
263+
it('writes encoded spaces in the query as +', () => {
264+
expect(parseURL('/a%20b?q=a%20b&%20=+')).toMatchObject({
265+
fullPath: '/a%20b?q=a+b&+=+',
266+
query: { q: ['a b'], ' ': [' '] },
267+
})
268+
})
269+
270+
it('encodes \\ in the query and hash like stringifyQuery() and encodeHash()', () => {
271+
expect(parseURL('/a\\b?q=a\\b#a\\b')).toMatchObject({
272+
fullPath: '/a/b?q=a%5Cb#a%5Cb',
273+
query: { q: ['a\\b'] },
274+
hash: '#a%5Cb',
275+
})
276+
})
277+
278+
it('keeps percent encoded sequences and lone %', () => {
279+
expect(parseURL('/a%2Fb/%e9/100%?q=%25#%20%')).toMatchObject({
280+
fullPath: '/a%2Fb/%e9/100%?q=%25#%20%',
281+
})
282+
})
283+
284+
it('resolves dot segments anywhere in the path', () => {
285+
expect(parseURL('/a/./b/../c').path).toBe('/a/c')
286+
expect(parseURL('/a/%2e%2e/b').path).toBe('/b')
287+
})
288+
289+
it('ignores the current location for absolute paths', () => {
290+
expect(parseURL('/foo', '/parent/current').path).toBe('/foo')
291+
})
292+
293+
it('keeps host and scheme like strings as paths', () => {
294+
expect(parseURL('//evil.com/x').path).toBe('//evil.com/x')
295+
// like browsers, `\\` is `/`
296+
expect(parseURL('/\\evil.com/x').path).toBe('//evil.com/x')
297+
expect(parseURL('javascript:alert(1)', '/parent/current').path).toBe(
298+
'/parent/javascript:alert(1)'
299+
)
300+
})
256301
})
257302

258303
it('uses the parseQuery result as query', () => {
259304
const query = { custom: ['value'] }
260305
expect(originalParseURL(() => query, '/foo?x').query).toBe(query)
261306
})
262307

263-
it('does not call parseQuery for a ? in the hash', () => {
264-
const parseQuery = vi.fn()
265-
expect(originalParseURL(parseQuery, '/foo#a?b').query).toEqual({})
266-
expect(parseQuery).not.toHaveBeenCalled()
267-
})
268-
269308
describe('hash', () => {
270309
it('keeps the hash as it appears in the URL, like location.hash', () => {
271310
expect(parseURL('/foo#%22%20%25')).toMatchObject({
@@ -293,6 +332,17 @@ describe('parseURL', () => {
293332
})
294333
})
295334

335+
describe('parseEncodedURL', () => {
336+
it('does not normalize the location', () => {
337+
expect(parseEncodedURL(parseQuery, '/a/./café b?q=a b#h b')).toEqual({
338+
fullPath: '/a/./café b?q=a b#h b',
339+
path: '/a/./café b',
340+
hash: '#h b',
341+
query: { q: ['a b'] },
342+
})
343+
})
344+
})
345+
296346
describe('stringifyURL', () => {
297347
it('joins path, query and hash', () => {
298348
expect(stringifyURL(stringifyQuery, '/foo', { a: ['1', '2'] }, '#h')).toBe(

0 commit comments

Comments
 (0)