Skip to content

Search, API & Pagination

Search, API endpoints, and pagination are all common features in a real-world website. Let’s see how to build them in Astro.

For a simple, static website, the easiest way to add search is:

  • Build a list of all your posts ahead of time (at build time).
  • Let the search happen in the browser, using a small bit of JavaScript (this is what we earlier called a “JS island”).

Here’s a basic search form to get started:

---
---
<!-- action is used for specifying the URL where the form data will be sent. Here it will send to /articles/search.astro page we dont need to write ".astro" in actions -->
<form method="GET" action="/articles/search">
<input type="text" id="search" placeholder="Search..." />
<input type="submit" value="Search" />
</form>

In plain words: when someone types a search term and presses submit, the browser sends them to /articles/search, along with whatever they typed, as part of the URL. The search.astro page on the receiving end can then read that search term and show matching results.

Sometimes you need your website to have its own little “backend” - a URL that returns data (usually as JSON) instead of an HTML page. Astro lets you build these easily.

// src/pages/api/search.json.ts
export async function GET() {
return new Response(JSON.stringify({ ok: true }));
}

In plain words: this file creates a URL endpoint (something like /api/search.json) that, when visited, runs this GET() function and sends back a response. This code only ever runs on the server - it never runs in the visitor’s browser, which makes it a safe place to do things like check passwords or talk to a database.

Pagination just means splitting up a long list of items (like blog posts) into separate pages, instead of showing everything at once.

Page 1 -> items 0-9
Page 2 -> items 10-19

In code, that logic looks like this:

const start = (page - 1) * limit;
posts.slice(start, start + limit);

In plain words: limit is how many posts you want per page (for example, 10). start is the position in your full list of posts where this particular page should begin. So for page 1, start is 0. For page 2 (with a limit of 10), start becomes 10, and so on.

Showing or Hiding “Previous” and “Next” Buttons

Section titled “Showing or Hiding “Previous” and “Next” Buttons”

You don’t want a “Previous” button to show up on page 1 (since there’s no page before it). Here’s a simple way to only show the button when it actually makes sense:

{page > 1 && <a href={`/page/${page-1}`}>Prev</a>}

In plain words: this line only shows the “Prev” link if the current page number is greater than 1. The same idea applies to a “Next” button - you’d check that there are actually more posts left to show, before displaying that link.