Skip to content

Commit 1ea55a1

Browse files
committed
feat: Sort search params keys
1 parent 9dc148f commit 1ea55a1

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

packages/nuqs/src/url-encoding.test.ts

+23
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,29 @@ describe('url-encoding/renderQueryString', () => {
9999
'?name=John+Doe&email=foo.bar%2Begg-spam@example.com&message=Hello,+world!+%23greeting'
100100
)
101101
})
102+
test('it sorts keys', () => {
103+
const search = new URLSearchParams()
104+
search.set('a', '3')
105+
search.set('b', '2')
106+
search.set('c', '1')
107+
const query = renderQueryString(search)
108+
expect(query).toBe('?a=3&b=2&c=1')
109+
})
110+
test('it preserves order of keys with the same name', () => {
111+
const search = new URLSearchParams()
112+
search.set('a', '3')
113+
search.append('a', '2')
114+
search.append('a', '1')
115+
const query = renderQueryString(search)
116+
expect(query).toBe('?a=3&a=2&a=1')
117+
})
118+
test('it sorts by unicode code points', () => {
119+
const search = new URLSearchParams()
120+
search.set('😊', 'foo')
121+
search.set('a', 'foo')
122+
const query = renderQueryString(search)
123+
expect(query).toBe('?a=foo&😊=foo')
124+
})
102125
test('practical use-cases', () => {
103126
// https://github.com/47ng/nuqs/issues/355
104127
{

packages/nuqs/src/url-encoding.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@ export function renderQueryString(search: URLSearchParams) {
22
if (search.size === 0) {
33
return ''
44
}
5+
6+
const clonedSearch = new URLSearchParams(search)
7+
clonedSearch.sort()
8+
const entries = clonedSearch.entries()
9+
510
const query: string[] = []
6-
for (const [key, value] of search.entries()) {
11+
for (const [key, value] of entries) {
712
// Replace disallowed characters in keys,
813
// see https://github.com/47ng/nuqs/issues/599
914
const safeKey = key

0 commit comments

Comments
 (0)