0
# Query String Handling
1
2
Comprehensive query string parsing and manipulation with support for arrays, nested objects, and complex data types. Includes built-in protection against prototype pollution and flexible serialization options for different data structures.
3
4
## Capabilities
5
6
### Parse Query String
7
8
Converts query strings into structured objects with automatic handling of duplicate keys and arrays.
9
10
```typescript { .api }
11
/**
12
* Parses and decodes a query string into an object
13
* @param parametersString - Query string with or without leading '?'
14
* @returns Parsed query object with string/array values
15
*/
16
function parseQuery<T extends ParsedQuery = ParsedQuery>(parametersString?: string): T;
17
18
type ParsedQuery = Record<string, string | string[]>;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { parseQuery } from "ufo";
25
26
// Basic query parsing
27
const basic = parseQuery("name=John&age=30&active=true");
28
// { name: 'John', age: '30', active: 'true' }
29
30
// With leading question mark
31
const withQ = parseQuery("?search=javascript&category=web");
32
// { search: 'javascript', category: 'web' }
33
34
// Array handling (duplicate keys)
35
const arrays = parseQuery("tags=javascript&tags=web&tags=api");
36
// { tags: ['javascript', 'web', 'api'] }
37
38
// URL-encoded values
39
const encoded = parseQuery("message=hello%20world&special=%21%40%23");
40
// { message: 'hello world', special: '!@#' }
41
42
// Empty and special cases
43
const empty = parseQuery("key1=&key2=value&key3");
44
// { key1: '', key2: 'value', key3: '' }
45
```
46
47
### Stringify Query Object
48
49
Converts query objects back into query string format with proper encoding.
50
51
```typescript { .api }
52
/**
53
* Stringifies and encodes a query object into a query string
54
* @param query - Object with string, number, boolean, array, or object values
55
* @returns Encoded query string without leading '?'
56
*/
57
function stringifyQuery(query: QueryObject): string;
58
59
type QueryObject = Record<string, QueryValue | QueryValue[]>;
60
type QueryValue = string | number | undefined | null | boolean | Array<QueryValue> | Record<string, any>;
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { stringifyQuery } from "ufo";
67
68
// Basic object to query string
69
const basic = stringifyQuery({ name: "John", age: 30, active: true });
70
// "name=John&age=30&active=true"
71
72
// Array values
73
const arrays = stringifyQuery({ tags: ["javascript", "web", "api"] });
74
// "tags=javascript&tags=web&tags=api"
75
76
// Complex objects (JSON stringified)
77
const complex = stringifyQuery({
78
user: { name: "John", email: "john@example.com" },
79
preferences: ["dark-mode", "notifications"]
80
});
81
// "user=%7B%22name%22%3A%22John%22%2C%22email%22%3A%22john%40example.com%22%7D&preferences=dark-mode&preferences=notifications"
82
83
// Filtering undefined values
84
const filtered = stringifyQuery({ a: "value", b: undefined, c: null });
85
// "a=value&c=null" (undefined values are filtered out)
86
```
87
88
### Encode Query Item
89
90
Encodes individual query key-value pairs with proper array handling.
91
92
```typescript { .api }
93
/**
94
* Encodes a pair of key and value into a URL query string format
95
* @param key - Query parameter key
96
* @param value - Value(s) to encode, can be single value or array
97
* @returns Encoded query string segment
98
*/
99
function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string;
100
```
101
102
**Usage Examples:**
103
104
```typescript
105
import { encodeQueryItem } from "ufo";
106
107
// Single value
108
const single = encodeQueryItem("name", "John Doe");
109
// "name=John+Doe"
110
111
// Array values
112
const array = encodeQueryItem("colors", ["red", "green", "blue"]);
113
// "colors=red&colors=green&colors=blue"
114
115
// Special value types
116
const number = encodeQueryItem("count", 42);
117
// "count=42"
118
119
const boolean = encodeQueryItem("active", true);
120
// "active=true"
121
122
// Empty or null values
123
const empty = encodeQueryItem("empty", "");
124
// "empty="
125
126
const nullValue = encodeQueryItem("null", null);
127
// "null"
128
129
// Object values (JSON stringified)
130
const object = encodeQueryItem("data", { key: "value" });
131
// "data=%7B%22key%22%3A%22value%22%7D"
132
```
133
134
135
## Security Features
136
137
### Prototype Pollution Protection
138
139
The parseQuery function includes built-in protection against prototype pollution attacks:
140
141
```typescript
142
// These dangerous keys are automatically ignored
143
parseQuery("__proto__=malicious&constructor=bad&normal=good");
144
// { normal: 'good' } - dangerous keys filtered out
145
```
146
147
### Safe Encoding
148
149
All encoding functions handle edge cases gracefully:
150
151
- Invalid input types are converted to strings
152
- Malformed encoding doesn't throw errors
153
- Special characters are properly escaped
154
- Unicode characters are handled correctly
155
156
## Advanced Usage Patterns
157
158
### Building Search URLs
159
160
```typescript
161
import { withQuery } from "ufo"; // From utilities module
162
163
const searchUrl = withQuery("/search", {
164
q: "javascript tutorials",
165
category: "programming",
166
tags: ["beginner", "web"],
167
limit: 20
168
});
169
// "/search?q=javascript+tutorials&category=programming&tags=beginner&tags=web&limit=20"
170
```
171
172
### Processing Form Data
173
174
```typescript
175
import { parseQuery, stringifyQuery } from "ufo";
176
177
// Parse form data from URL
178
const formData = parseQuery(window.location.search.slice(1));
179
180
// Modify and rebuild
181
const updatedData = {
182
...formData,
183
page: parseInt(formData.page as string) + 1,
184
timestamp: Date.now()
185
};
186
187
const newQueryString = stringifyQuery(updatedData);
188
```
189
190
### API Parameter Handling
191
192
```typescript
193
import { stringifyQuery } from "ufo";
194
import { getQuery } from "ufo"; // getQuery is in utilities module
195
196
// Extract API parameters
197
const apiParams = getQuery(request.url);
198
199
// Add server-side parameters
200
const enrichedParams = {
201
...apiParams,
202
apiKey: process.env.API_KEY,
203
version: "v2"
204
};
205
206
// Build API request URL
207
const apiUrl = `https://api.service.com/data?${stringifyQuery(enrichedParams)}`;
208
```