URL Query Parameters Explained
A practical guide to URL query parameters and query strings, covering syntax, encoding, repeated parameters, arrays, filtering, sorting, pagination, UTM parameters, JavaScript APIs and common mistakes.
Query parameters are one of the most common ways websites and APIs pass additional information through a URL. They are used for searches, filters, sorting, pagination, tracking, feature flags, API requests and many other tasks.
A URL such as https://example.com/products?category=books&page=2 contains more information than just the destination. Everything after the question mark is the query component, and the individual name-value pairs inside it are query parameters.
Understanding query parameters is important for frontend developers because they appear everywhere: browser navigation, REST APIs, search pages, Next.js routes, analytics links and third-party integrations. This guide explains how query strings work, how to construct and parse them, and how to avoid the most common mistakes.
What Are URL Query Parameters?
A query parameter is a piece of data attached to a URL, usually in the form name=value. Multiple parameters are separated by an ampersand.
https://example.com/products?category=books&page=2In this example, category and page are query parameter names, while books and 2 are their corresponding values.
| Part | Example | Purpose |
|---|---|---|
| Base URL | https://example.com/products | Identifies the resource or page |
| Query start | ? | Begins the query component |
| Parameter | category=books | Provides one named value |
| Separator | & | Separates multiple parameters |
| Parameter | page=2 | Provides another named value |
What Is a Query String?
The terms query string and query parameters are often used interchangeably, but they can describe slightly different things. The query string generally refers to the entire portion after the question mark, while query parameters are the individual key-value pairs within it.
?category=books&page=2&sort=priceHere the complete query string is ?category=books&page=2&sort=price. The individual parameters are category=books, page=2 and sort=price.
Basic Query Parameter Syntax
The basic syntax is straightforward: a question mark starts the query component, an equals sign separates a name from its value, and ampersands separate multiple parameters.
https://example.com/search?q=javascript&language=en&page=3This URL contains three parameters: q, language and page.
- The ? starts the query component.
- The = separates a parameter name from its value.
- The & separates multiple parameters.
- Parameter names and values are normally URL-encoded when necessary.
- The order of parameters may or may not matter depending on the application.
Query Parameters Are Usually Optional
A URL can normally exist without any query parameters. The query component adds additional information to the request but is not necessarily required.
https://example.com/products
https://example.com/products?category=booksThe first URL points to the products resource without additional filtering information. The second provides a category that the application can use to change the result.
Query Parameters vs Path Parameters
Paths and query parameters can both carry information, but they commonly serve different purposes. A path often identifies a particular resource, while query parameters commonly modify how that resource is retrieved, filtered or represented.
| URL component | Example | Typical purpose |
|---|---|---|
| Path | /products/123 | Identify a specific resource |
| Query parameter | ?sort=price | Modify or filter a request |
| Query parameter | ?page=2 | Select a result page |
| Query parameter | ?format=json | Request a particular representation |
There is no universal rule that every application must follow, but this distinction is useful when designing readable URLs and APIs.
Common Uses of Query Parameters
Query parameters are extremely flexible. Some of the most common uses include:
- Search queries.
- Filtering.
- Sorting.
- Pagination.
- Selecting a language or locale.
- Changing the requested representation.
- Applying UI state.
- Analytics and marketing tracking.
- API options.
- Feature flags and temporary application state.
Search Parameters
Search pages commonly use a parameter such as q, query or search to represent the user's search text.
https://example.com/search?q=frontend%20developmentThe value may contain spaces, punctuation or Unicode characters, so it needs appropriate URL encoding. In application code, URLSearchParams can handle the serialization.
Filtering with Query Parameters
Query parameters are particularly useful for filtering collections.
https://example.com/products?category=books&priceMax=50The server or client can interpret these parameters and return products matching the requested conditions.
For more complex filtering systems, applications may use several parameters or a structured naming convention.
https://example.com/products?category=books&minPrice=10&maxPrice=50&sort=priceSorting
Sorting is another common use. A parameter can specify both the field and direction.
https://example.com/products?sort=price&order=ascThe exact parameter names are application-specific. Some APIs use sort=price:asc, while others use separate sort and direction parameters.
Pagination
Pagination parameters allow a client to request a particular subset of a larger collection.
https://example.com/products?page=3&limit=24Another common approach uses offset and limit.
https://api.example.com/products?offset=48&limit=24Cursor-based APIs may instead use a cursor parameter.
https://api.example.com/products?cursor=eyJpZCI6MTIzfQThe cursor itself may be an opaque value generated by the server. Clients should generally treat it as data rather than trying to interpret or modify it.
UTM Query Parameters
UTM parameters are a widely used convention for marketing and analytics tracking. They are added to URLs to provide information about where a visit originated or which campaign generated it.
https://example.com/pricing?utm_source=newsletter&utm_medium=email&utm_campaign=summer| Parameter | Typical meaning |
|---|---|
| utm_source | Traffic source |
| utm_medium | Marketing medium |
| utm_campaign | Campaign name |
| utm_term | Usually associated with paid search terms |
| utm_content | Differentiate ads or links within a campaign |
UTM parameters are still query parameters from the URL's perspective. Their special behavior comes from analytics systems that recognize the utm_* naming convention.
Repeated Query Parameters
A query string can contain the same parameter name more than once.
https://example.com/products?tag=javascript&tag=react&tag=nextjsThis can represent a list of values. However, the exact interpretation depends on the server or framework. Some systems return all values, some use only the first or last value, and others apply their own conventions.
In JavaScript, URLSearchParams supports repeated parameters explicitly.
const params = new URLSearchParams();
params.append("tag", "javascript");
params.append("tag", "react");
params.append("tag", "nextjs");
console.log(params.getAll("tag"));Arrays in Query Parameters
There is no single universal syntax for arrays in query strings. Different APIs use different conventions.
| Style | Example |
|---|---|
| Repeated parameter | ?tag=js&tag=react&tag=nextjs |
| Comma-separated | ?tag=js,react,nextjs |
| Bracket notation | ?tag[]=js&tag[]=react |
| Indexed notation | ?tag[0]=js&tag[1]=react |
| JSON value | ?tag=%5B%22js%22%2C%22react%22%5D |
When designing an API, choose one representation and document it clearly. Clients should not have to guess how arrays are represented.
Boolean Query Parameters
Boolean values can also be represented in query parameters.
https://example.com/products?inStock=true&featured=falseThe server needs to define how boolean values are interpreted. Explicit true and false values are usually easier to understand than relying on the presence or absence of a parameter unless the API intentionally uses presence as a flag.
Parameters Without Values
A query string can contain a parameter without an explicit value.
https://example.com/products?debugSome systems interpret this as a boolean flag. Other applications may expect debug=1 or debug=true instead. There is no universal application-level meaning, so the receiving system determines how the parameter is interpreted.
Empty Parameter Values
An empty value is different from a parameter that does not appear at all.
https://example.com/search?q=An application may interpret q= as an explicitly empty search term, while a missing q parameter may mean that no search was requested. APIs should document such distinctions when they matter.
URL Encoding in Query Parameters
Query parameter names and values are data inside a URL structure. Characters that have special meaning in the query syntax may therefore need to be percent-encoded.
https://example.com/search?q=rock%26rollHere %26 represents an ampersand that belongs to the q value. Without encoding, the ampersand could be interpreted as the separator between parameters.
Why Spaces Become Encoded
Spaces cannot normally be represented as literal spaces in a URL. Depending on the serialization format, they can appear as %20 or, in application/x-www-form-urlencoded contexts, as +.
q=red%20shoes
q=red+shoesThe exact representation depends on the API or serialization mechanism being used. Browser URL APIs should generally be preferred over manual replacement of spaces.
Building Query Parameters with URLSearchParams
URLSearchParams is a browser and JavaScript API designed specifically for working with URL query parameters. It handles serialization and encoding for you.
const params = new URLSearchParams();
params.set("q", "red shoes");
params.set("category", "men's shoes");
params.set("page", "2");
console.log(params.toString());This is safer than manually concatenating parameter names, values and ampersands.
set() vs append()
URLSearchParams provides both set() and append(), and they have different behavior.
const params = new URLSearchParams();
params.set("tag", "javascript");
params.set("tag", "react");
console.log(params.toString());set() replaces the existing value for that name. If multiple values are required, use append().
const params = new URLSearchParams();
params.append("tag", "javascript");
params.append("tag", "react");
console.log(params.toString());When reading repeated parameters, getAll() returns all values.
const params = new URLSearchParams(
"tag=javascript&tag=react&tag=nextjs"
);
const tags = params.getAll("tag");Reading Query Parameters from a URL
The URL class provides searchParams for accessing the query component.
const url = new URL(
"https://example.com/products?category=books&page=2"
);
const category = url.searchParams.get("category");
const page = url.searchParams.get("page");The values returned by searchParams.get() are strings. If an application expects a number, it should explicitly validate and convert the value.
Validating Query Parameters
A query parameter comes from the URL and should generally be treated as untrusted input. Even when a parameter is expected to contain a number, enum value or identifier, the application should validate it.
const pageParam = url.searchParams.get("page");
const page = Number(pageParam);
if (!Number.isInteger(page) || page < 1) {
throw new Error("Invalid page parameter");
}Validation is especially important for API endpoints, database queries, sorting options, pagination and access-controlled resources.
Query Parameters Are Strings
One of the easiest mistakes to make is assuming that query parameters automatically have JavaScript types. URLs contain textual representations, so values normally arrive as strings.
const params = new URLSearchParams("?page=2&active=true");
const page = params.get("page");
const active = params.get("active");The values are not automatically a number and boolean. The application has to parse them according to its own validation rules.
Query Parameters in APIs
REST APIs frequently use query parameters for filtering, sorting, pagination and optional behavior.
GET /api/products?category=books&page=2&limit=20 HTTP/1.1A server might interpret category as a filter and page and limit as pagination controls. Query parameters allow clients to modify a request without changing the underlying resource path.
Optional vs Required Query Parameters
APIs should document whether a parameter is optional or required. Optional parameters can have defaults, while required parameters must be supplied for the request to be meaningful.
| Parameter | Required? | Example |
|---|---|---|
| page | Optional | Defaults to 1 |
| limit | Optional | Defaults to 20 |
| userId | Required | Must identify a user |
| sort | Optional | Defaults to relevance |
Default Values
A useful API design pattern is to give optional query parameters sensible defaults.
GET /products
GET /products?page=1&limit=20Both requests can represent the same default state if the API defines page=1 and limit=20 as defaults.
Query Parameter Ordering
The order of query parameters usually does not change their semantic meaning. These URLs can represent the same set of parameters:
https://example.com/products?page=2&sort=price
https://example.com/products?sort=price&page=2However, applications, caches, signatures and analytics systems can sometimes treat complete URLs as distinct strings. If canonical URLs or request signing matter, parameter ordering should be handled consistently.
Duplicate Parameters Can Be Ambiguous
Repeated parameters are valid in many contexts, but their interpretation must be defined by the receiving application.
https://example.com/products?page=2&page=5Should page be 2, 5, both, or invalid? Different frameworks can make different choices. APIs should avoid ambiguity unless repeated parameters are deliberately supported.
Query Parameters and Browser Navigation
Query parameters are useful for representing state that should be preserved in a link. For example, a filtered product list can use query parameters so another person can open exactly the same filtered view.
https://example.com/products?category=books&sort=price&page=2This makes the state shareable, bookmarkable and directly accessible through browser navigation.
Query Parameters in React Applications
React applications often use query parameters to represent search, filtering, sorting and pagination state.
const params = new URLSearchParams();
params.set("category", category);
params.set("sort", sort);
params.set("page", String(page));
const href = `/products?${params.toString()}`;Keeping this state in the URL can make application behavior easier to share and restore. It also means browser back and forward navigation can represent meaningful state changes.
Query Parameters in Next.js
Next.js applications commonly use query parameters for search pages, filters, pagination and other URL-driven state. In the App Router, server components can receive search parameters through the page's searchParams prop, while client components can use browser-oriented routing APIs such as useSearchParams.
export default function ProductsPage({
searchParams,
}: {
searchParams: Promise<{
category?: string;
page?: string;
}>;
}) {
return null;
}The exact Next.js API can change between framework versions, so application code should follow the conventions of the installed Next.js release. The underlying URL concept remains the same: the query component contains URL-encoded key-value data.
Query Parameters and SEO
Query parameters can be useful for SEO when they represent meaningful, indexable variations of a page. They can also create many URLs that expose essentially the same content.
For example, a website might have URLs such as:
https://example.com/products
https://example.com/products?sort=price
https://example.com/products?sort=name
https://example.com/products?utm_source=newsletterNot every variation should necessarily be treated as a separate canonical page. Tracking parameters such as UTM tags generally describe traffic acquisition rather than different content. SEO handling should therefore be planned around the site's actual content model.
Tracking Parameters and Canonical URLs
Marketing parameters can create many URL variants without changing the underlying page content.
https://example.com/article
https://example.com/article?utm_source=email&utm_campaign=launchFor SEO-sensitive pages, sites commonly use canonicalization and other search-engine directives so tracking variations do not unnecessarily become separate indexable versions.
Do Query Parameters Affect Caching?
They can. HTTP caches and application caches often consider the complete URL, including the query component, when determining whether two requests are the same cache key.
/products?page=1
/products?page=2These are different URLs and may therefore represent different cached responses. Applications should be aware of query parameters when designing cache keys, invalidation rules and CDN behavior.
Sensitive Data in Query Parameters
A query parameter is not private simply because it is not displayed prominently in the page. If sensitive information must be transmitted, use an appropriate secure mechanism rather than relying on URL obscurity or URL encoding.
Query Parameters Are Not Encryption
URL encoding changes representation; it does not provide confidentiality. For example, q=hello%20world is simply an encoded representation of q=hello world.
Anyone who can see the URL can generally decode its query parameters. This is why query parameters should be considered visible request data.
Validating and Sanitizing Input
Query parameters should be validated before they influence database queries, filesystem operations, sorting logic, redirects or authorization decisions.
- Validate numeric parameters as numbers and enforce reasonable ranges.
- Restrict enum parameters to supported values.
- Validate identifiers before using them in database operations.
- Do not directly trust sort or filter fields supplied by clients.
- Apply authorization checks independently of query parameters.
- Use parameterized database queries rather than constructing SQL from raw URL values.
Query Parameters and SQL Injection
Encoding a query parameter in a URL does not make it safe for a database. The URL layer and database layer have different parsing rules.
If a parameter is later incorporated into a SQL statement, the application must use appropriate database parameterization and validation. URL encoding is not a substitute for SQL injection defenses.
Common Query Parameter Mistakes
- Manually concatenating query strings without encoding values.
- Forgetting the ? before the first query parameter.
- Using & incorrectly inside a parameter value.
- Confusing query parameters with path parameters.
- Assuming every parameter is automatically a number or boolean.
- Using duplicate parameter names without defining their meaning.
- Using different array conventions in different API endpoints.
- Putting secrets into query strings.
- Failing to validate user-controlled parameters.
- Encoding an already encoded value.
- Ignoring query parameters when designing cache keys.
- Creating unnecessary URL variants that complicate SEO.
Manual Query String Construction
Manually constructing a query string may look convenient for simple cases.
const url =
"/products?category=" +
encodeURIComponent(category) +
"&page=" +
encodeURIComponent(String(page));This can work, but as the number of parameters grows it becomes easier to introduce missing separators, incorrect encoding or accidental undefined values.
A Better Approach with URLSearchParams
const params = new URLSearchParams({
category,
page: String(page),
sort,
});
const url = `/products?${params.toString()}`;The structured approach is easier to extend and makes the encoding responsibility explicit.
Removing Query Parameters
URLSearchParams also makes it easy to remove parameters without manipulating the complete URL string.
const url = new URL(
"https://example.com/products?category=books&page=2"
);
url.searchParams.delete("page");
console.log(url.toString());Updating Existing Parameters
const url = new URL(
"https://example.com/products?page=2&sort=price"
);
url.searchParams.set("page", "3");
console.log(url.toString());This is safer than trying to replace page=2 with page=3 using string operations because the URL API understands the query structure.
Query Parameters and URL State
One of the biggest advantages of query parameters is that they can make application state part of a shareable URL.
https://example.com/tools?category=security&sort=popular&page=2A user can copy the URL, open it later or send it to another person and preserve the same filtering and pagination state, assuming the application supports those parameters.
When Query Parameters Are a Good Choice
- The state should be shareable through a URL.
- The state should survive page reloads.
- Users should be able to bookmark the current view.
- Browser back and forward navigation should preserve state.
- The value modifies how a collection is displayed or retrieved.
- The value represents search, filtering, sorting or pagination.
- The information is safe to expose in a URL.
When Query Parameters May Not Be Appropriate
- The value is a secret or sensitive credential.
- The data is too large for practical URL usage.
- The state should not be shareable or visible.
- The value represents the identity of a resource better expressed as a path.
- The application needs to send a complex request body rather than URL metadata.
Query Parameters vs Request Body
For HTTP APIs, query parameters are commonly used for request options such as filtering, sorting and pagination, while request bodies are commonly used to send larger or more structured data for operations such as creating or updating resources.
| Use case | Common location |
|---|---|
| Filtering a collection | Query parameters |
| Pagination | Query parameters |
| Sorting | Query parameters |
| Search | Query parameters |
| Creating a complex resource | Request body |
| Updating structured data | Request body |
| Authentication secret | Secure authentication mechanism, not a query string |
Query Parameter Naming
Consistent parameter names make APIs easier to understand and maintain. Names should clearly describe the value and follow one convention throughout the API.
| Purpose | Example |
|---|---|
| Search | q |
| Page | page |
| Page size | limit |
| Sort field | sort |
| Sort direction | order |
| Category | category |
There is no requirement to use these exact names. The important part is consistency and clear documentation.
Keep Query Parameters Predictable
An API becomes easier to use when similar concepts are represented consistently. If one endpoint uses page and another uses pageNumber for the same concept, clients have to remember unnecessary differences.
Debugging Query Parameters
When a URL behaves unexpectedly, inspect the actual query string rather than only the application UI. Look for missing parameters, incorrect encoding, duplicate names, unexpected empty values and accidental double encoding.
const url = new URL(window.location.href);
for (const [key, value] of url.searchParams) {
console.log(key, value);
}This makes it easier to see what the browser actually parsed from the URL.
Query Parameter Checklist
- Use ? only once to start the query component.
- Separate parameters with &.
- Encode parameter names and values when necessary.
- Use URLSearchParams or URL for application code.
- Define how repeated parameters are interpreted.
- Choose and document one array representation.
- Validate numeric, boolean and enum values.
- Keep sensitive data out of URLs.
- Consider cache behavior when query parameters affect responses.
- Consider SEO implications for publicly indexable URLs.
- Use consistent parameter naming conventions.
Frequently Asked Questions
What is a URL query parameter?
A query parameter is a named value attached to a URL, usually using the name=value format. For example, ?page=2 contains the parameter page with the value 2.
What is the difference between a query string and query parameters?
The query string is the complete query component after the question mark, while query parameters are the individual name-value pairs contained within it.
How are multiple query parameters separated?
Multiple parameters are normally separated with an ampersand. For example, ?category=books&page=2 contains two parameters.
Can a URL have the same query parameter more than once?
Yes. Repeated parameters are commonly used to represent multiple values, but the receiving application must define how those values are interpreted.
How should I build query parameters in JavaScript?
For most application code, URLSearchParams is a good choice because it handles serialization and URL encoding without requiring manual concatenation.
Are query parameters secure?
Query parameters are visible URL data and should not be used for secrets. URLs may be stored in browser history, logs, analytics systems and other infrastructure.
Do query parameters affect SEO?
They can. Different query strings can create different URL variants, so websites should decide which parameter combinations represent meaningful pages and which are merely tracking or temporary state.
Helpful Query Parameter Tools
A URL Query String Parser is useful when you need to inspect an existing URL and see its individual parameters and values. A Query Parameter Builder helps construct query strings from structured values, while a Query Parameter Decoder is useful when debugging percent-encoded parameter data. A URL Builder can assemble a complete URL from its components, and a UTM Builder can generate campaign URLs with consistent tracking parameters for marketing and analytics.
Conclusion
URL query parameters provide a simple and flexible way to attach additional data to a URL. They are commonly used for search, filtering, sorting, pagination, tracking and API options.
The basic syntax is simple, but reliable handling requires more than concatenating strings. Parameter values should be encoded correctly, repeated parameters and arrays should have defined conventions, and values received from URLs should be validated before they influence application behavior.
For JavaScript applications, URL and URLSearchParams provide structured APIs for creating, reading, updating and deleting query parameters. Using these APIs reduces manual encoding errors and makes URL-driven application state easier to maintain.
Finally, remember that query parameters are part of a visible URL. They should contain information that is appropriate to expose, while secrets and sensitive credentials should be handled through dedicated security mechanisms instead.