#SSR with search query and what happens if there are like 100 results and I want to do pages
4 messages · Page 1 of 1 (latest)
Hi @fallow talon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
SSR with Search Query Params + URL-based Pagination
For SSR (on-demand rendering), you cannot use getStaticPaths() or the built-in paginate() helper — those are only for static builds. Instead, you handle everything manually using Astro.params and Astro.url (for query strings).
Here's how you can approach this with a route like src/pages/search/[page].astro:
---
export const prerender = false; // Not needed if already in 'server' mode
// 1. Get the page number from the URL path (e.g. /search/2)
const { page } = Astro.params;
const currentPage = page ? parseInt(page) : 1;
const pageSize = 10;
// 2. Get the search query from query params (e.g. ?q=astro)
const query = Astro.url.searchParams.get('q') ?? '';
// 3. Fetch your data (example with a generic API)
const response = await fetch(`<https://your-api.com/search?q=${query}&page=${currentPage}&size=${pageSize}`>);
const { results, total } = await response.json();
const lastPage = Math.ceil(total / pageSize);
// 4. Redirect if page is out of range
if (currentPage > lastPage) {
return Astro.redirect('/404');
}
---
<h1>Search results for: {query}</h1>
<p>Page {currentPage} of {lastPage}</p>
<ul>
{results.map((item) => <li>{item.name}</li>)}
</ul>
<!-- Pagination links, preserving the search query -->
{currentPage > 1 && (
<a href={`/search/${currentPage - 1}?q=${query}`}>Previous</a>
)}
{currentPage < lastPage && (
<a href={`/search/${currentPage + 1}?q=${query}`}>Next</a>
)}
Key points
Astro.params.pagegives you the path segment (e.g.2from/search/2). [Dynamic routes]Astro.url.searchParamslets you read query parameters like?q=your+query— this is standard Web API available in SSR pages.- You manually compute
lastPageand build prev/next links, appending the?q=param so the search term is preserved across pages. - Since these are SSR routes, no
getStaticPaths()is needed — the page is rendered on request for any matching route. [On-demand routes]