Query Strings

`Astro.url.searchParams` Reads the `?key=value` Bits

Query Strings

Query string parameters live on `Astro.url.searchParams`. Useful for filtering and pagination on server-rendered pages.

3 min read Level 1/5 #astro#query-strings#url
What you'll learn
  • Read query params with `Astro.url.searchParams`
  • Handle missing values
  • Know when this works (server pages)

Astro.url is the URL of the current request. Astro.url.searchParams is a standard URLSearchParams — exactly what the browser provides.

Reading a Param

---
const q = Astro.url.searchParams.get("q") ?? "";
const page = Number(Astro.url.searchParams.get("page") ?? "1");
---

<p>You searched for: {q || "(nothing)"}</p>
<p>Page {page}</p>

For /search?q=astro&page=2:

  • q"astro"
  • page2

For /search with no query: q"", page1.

Multiple Values

getAll(name) returns all values for a repeated key:

---
// /products?tag=js&tag=react&tag=web
const tags = Astro.url.searchParams.getAll("tag");
// tags === ["js", "react", "web"]
---

Iterate Every Param

---
const params = Astro.url.searchParams;
const entries = [...params.entries()];
---
<ul>
  {entries.map(([k, v]) => <li>{k}={v}</li>)}
</ul>

When Does It Work?

  • Static pages: query strings exist in the URL, but Astro serves the same pre-rendered HTML regardless. The server doesn’t see the query. You’d have to read them with JS on the client.
  • Server / SSR pages: every request triggers a re-render with the latest query. Astro.url.searchParams reflects the request.

For interactive filtering on static pages, use a small client-side script or a hydrated island.

---
const next = new URL(Astro.url);
next.searchParams.set("page", String(page + 1));
---
<a href={next.pathname + next.search}>Next page →</a>

new URL(Astro.url) clones it so you can mutate safely.

Up Next

Redirects.

Redirects →