- When You Don't Need a Search Service
- The Plan: Three Small Pieces
- Step 1: Build the Search Index as a Static Route Handler
- Step 2: Load the Dialog Only When Needed
- Step 3: Use a Native dialog Element
- Step 4: Simple Ranking That Feels Right
- Step 5: Keyboard Navigation and Accessibility
- Keep It Off the Critical Path
- Gotchas I Hit
- When to Upgrade to a Real Search Service
- Next.js Site Search Checklist
- My Recommendation
- Related Next.js Guides
- Frequently Asked Questions
- Conclusion
When a site grows past a few dozen pages, visitors start needing search. The usual advice is to sign up for a hosted search service. For a portfolio, a blog or a documentation site with a few hundred pages, that's often more than you need.
This guide shows how I built Next.js site search for my own portfolio, harshthummar.in: press Ctrl+K (or ⌘K, or /) anywhere, type, and jump straight to an article, case study or page. There's no third-party service, no monthly cost, and nothing extra loads until someone actually opens search.
It searches 61 pages from a 26 KB JSON file, and it's built from three small pieces you can copy.
When You Don't Need a Search Service
Hosted search services are excellent at scale: typo tolerance, analytics, millions of records. But they also mean an account, API keys, an indexing step and often a client library on every page.
A static, client-side search is a good fit when:
- Your content is in the repository or a CMS you build from (blog posts, docs, products).
- You have up to a few hundred pages.
- Results only need to match titles, summaries and keywords, not full article text.
If that sounds like your site, you can skip the service entirely.
The Plan: Three Small Pieces
- A static search index: a route handler that turns your content into JSON at build time.
- A lazy-loaded search dialog: its code and the index download only on first open.
- Keyboard shortcuts and navigation: Ctrl+K to open, arrow keys to move, Enter to go, Esc to close.
Each piece is small, and together they add almost nothing to normal page loads.
Step 1: Build the Search Index as a Static Route Handler
Create a route handler that reads your content and returns one array of entries. On my site the data lives in TypeScript files (data/blog.ts, data/casestudy.ts and so on), so the index is built from the same source as the pages themselves:
// app/search-index.json/route.ts
import { blogPosts } from "@/data/blog";
import { caseStudies } from "@/data/casestudy";
// Built once at build time, then served as a static file.
export const dynamic = "force-static";
type SearchEntry = { type: string; title: string; url: string; text: string; keywords: string };
export function GET() {
const entries: SearchEntry[] = [
...caseStudies.map((cs) => ({
type: "Case study",
title: cs.title,
url: `/casestudy/${cs.slug}`,
text: cs.subtitle,
keywords: [cs.category, ...cs.technologies].join(" "),
})),
...blogPosts.map((post) => ({
type: "Article",
title: post.title,
url: `/blog/${post.slug}`,
text: post.excerpt,
keywords: [post.category, ...(post.keywords ?? [])].join(" "),
})),
];
return Response.json(entries);
}The folder name search-index.json becomes the URL, so the file is served at /search-index.json. Because of force-static, the build output lists it as a static route. It's generated once, not on every request.
Keep the entries lean. I index titles, short summaries and keywords, not full article bodies. That keeps the file small (26 KB for 61 entries) while still matching what people actually type.
Step 2: Load the Dialog Only When Needed
The search button lives in the header, which is on every page. The dialog itself shouldn't be. Use next/dynamic with ssr: false inside your client header component, and only render the dialog after the first open:
"use client";
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
// Downloaded only when a visitor first opens search.
const SearchDialog = dynamic(() => import("@/components/search/SearchDialog"), { ssr: false });
export default function Header() {
const [open, setOpen] = useState(false);
const [mounted, setMounted] = useState(false);
if (open && !mounted) setMounted(true);
// Ctrl/Cmd+K anywhere, or "/" when not typing in a field.
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const typing =
event.target instanceof HTMLElement && event.target.closest("input, textarea, select, [contenteditable]");
if ((event.key === "k" && (event.ctrlKey || event.metaKey)) || (event.key === "/" && !typing)) {
event.preventDefault();
setOpen(true);
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, []);
return (
<header>
{/* …navigation… */}
<button type="button" onClick={() => setOpen(true)} aria-label="Search the site (Ctrl+K)">
Search
</button>
{mounted && <SearchDialog open={open} onClose={() => setOpen(false)} />}
</header>
);
}Two details matter here:
- The "/" shortcut checks where the focus is. Without that check, typing a slash in your contact form would open search.
- The dialog stays mounted after the first open. Opening it a second time is instant.
The index is fetched once per visit and cached in a module-level promise:
let indexPromise: Promise<Entry[]> | null = null;
const loadIndex = () =>
(indexPromise ??= fetch("/search-index.json")
.then((res) => (res.ok ? (res.json() as Promise<Entry[]>) : []))
.catch(() => {
indexPromise = null; // allow a retry next time
return [];
}));Step 3: Use a Native dialog Element
You don't need a modal library. The browser's <dialog> element, opened with showModal(), already gives you a backdrop, keeps keyboard focus inside the dialog and puts everything else on the page out of reach:
useEffect(() => {
const node = dialogRef.current;
if (!node) return;
if (open && !node.open) {
node.showModal();
inputRef.current?.select();
} else if (!open && node.open) {
node.close();
}
}, [open]);Style the backdrop with the ::backdrop pseudo-element:
.search-dialog::backdrop {
background: rgb(37 40 32 / 0.4);
backdrop-filter: blur(2px);
}Closing when someone clicks outside is one line: the click target is the dialog element itself only when the backdrop area is clicked.
<dialog ref={dialogRef} onClose={onClose} onClick={(e) => e.target === dialogRef.current && onClose()}>Step 4: Simple Ranking That Feels Right
For a few hundred entries, a small scoring function is plenty. Every word in the query must match somewhere, and matches in the title count more than matches in keywords or the summary:
const norm = (s: string) =>
s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}.+#]+/gu, " ").trim();
function search(entries: Entry[], query: string): Entry[] {
const q = norm(query);
if (!q) return [];
const words = q.split(" ");
const scored: { entry: Entry; score: number }[] = [];
for (const entry of entries) {
const title = norm(entry.title);
const keywords = norm(entry.keywords);
const text = norm(entry.text);
let score = 0;
let matchesAll = true;
for (const word of words) {
if (title.includes(word)) score += 10;
else if (keywords.includes(word)) score += 4;
else if (text.includes(word)) score += 3;
else {
matchesAll = false;
break;
}
}
if (!matchesAll) continue;
if (title.startsWith(q)) score += 20;
scored.push({ entry, score });
}
return scored.sort((a, b) => b.score - a.score).slice(0, 10).map((s) => s.entry);
}The normaliser keeps ., + and #, so searches like "next.js", "c++" or "c#" still work. On my site, typing "laravel" returns the Laravel REST API article first, followed by the two case studies built with Laravel, which is exactly the order a visitor would expect.
Step 5: Keyboard Navigation and Accessibility
Search is a keyboard feature, so the keyboard experience has to be complete. Keep focus in the input and move a "selected" index with the arrow keys:
const onKeyDown = (event: React.KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
onClose();
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!list.length) return;
setSelected((i) => (i + (event.key === "ArrowDown" ? 1 : -1) + list.length) % list.length);
} else if (event.key === "Enter" && list[selected]) {
event.preventDefault();
router.push(list[selected].url);
onClose();
}
};For screen readers, mark the input as a combobox that controls the results list, and point aria-activedescendant at the selected option:
<input
role="combobox"
aria-expanded={list.length > 0}
aria-controls="search-results"
aria-activedescendant={list[selected] ? `search-option-${selected}` : undefined}
/>
<ul id="search-results" role="listbox">
{list.map((item, i) => (
<li key={item.url} id={`search-option-${i}`} role="option" aria-selected={i === selected}>
…
</li>
))}
</ul>Also show something useful before anyone types (I show a few "Jump to" links), and a friendly message when nothing matches.
Keep It Off the Critical Path
The whole point is that search costs nothing until it's used, so verify it. Open your browser's Network tab, load a few pages, and confirm there's no request for /search-index.json or the dialog's JavaScript. Then press Ctrl+K and check that each one loads exactly once.
That's how I tested mine: normal page loads made zero search requests, and opening search fetched the index once per visit.
Gotchas I Hit
- Esc didn't always close the dialog. A native
<dialog>should close on Esc, but in my testing the browser's built-in behaviour didn't fire reliably every time, so I also handle Esc in the input's key handler. It costs one line. - The global focus ring boxed in the input. My site's focus style uses an outline plus a
box-shadow. Inside the search dialog it drew a box within a box and covered the divider line. I removed both for that one input, because the open dialog already shows where focus is. - Ctrl+K needs preventDefault. In some browsers Ctrl+K focuses the address bar's search, so call
event.preventDefault()when you handle it. - Don't steal "/" from forms. Check whether focus is in an input, textarea, select or editable element before opening search.
When to Upgrade to a Real Search Service
This approach has limits. Consider a hosted service when:
- You have thousands of pages, or the index file grows past a few hundred KB.
- You need full-text search across article bodies.
- You want typo tolerance, synonyms or search analytics.
Until then, the static index is faster to build, free to run and easier to maintain.
Next.js Site Search Checklist
- Route handler builds the index with
force-static - Index holds titles, summaries and keywords, not full article bodies
- Dialog loaded with
next/dynamicand rendered only after the first open - Index fetched once per visit and cached
- Native
<dialog>withshowModal(), a styled::backdropand click-outside to close - Ctrl/⌘+K and "/" open search; "/" ignored while typing in a field
- Arrow keys, Enter and Esc all work from the input
- Combobox roles and
aria-activedescendantfor screen readers - Network tab shows no search requests on normal page loads
My Recommendation
If your site has under a few hundred pages, build search yourself with a static index and a lazy-loaded dialog. You'll have it working in an afternoon, it costs nothing to run, and your normal page loads stay exactly as fast as they were.
Related Next.js Guides
- Next.js 16 Page Transitions With React View Transitions →Smooth page changes with no animation library.
- Next.js SEO Guide →Metadata, JSON-LD, sitemaps and llms.txt, generated from the same data.
- Next.js 16 Performance Optimization →Keep new features off the critical path.
- React 19 Hooks: useActionState and useOptimistic →Modern React patterns for interactive UI.
- React Server Components Explained →Where client components like a search dialog fit in the App Router.
Frequently Asked Questions
How do I add search to a Next.js site without Algolia?
Build a JSON index with a route handler that uses export const dynamic = "force-static", then load a search dialog with next/dynamic that fetches the index on first open and filters it in the browser.
Will client-side search slow down my Next.js site?
Not if you load it lazily. With next/dynamic and a fetch on first open, normal page loads don't download the search code or the index at all.
How do I add a Ctrl+K shortcut in React?
Listen for keydown on window, check for event.key === "k" with ctrlKey or metaKey, call event.preventDefault(), and open your search dialog.
How big can a static search index get?
It depends on what you index, but keeping titles, summaries and keywords only stays small. My index for 61 pages is about 26 KB. If yours grows past a few hundred KB, consider a hosted search service.
Is the HTML dialog element accessible?
Yes. A <dialog> opened with showModal() keeps focus inside the dialog and makes the rest of the page inert. Add combobox and listbox roles to the search input and results for screen readers.
Conclusion
You don't need a search service to give visitors great search. A static index from a route handler, a lazy-loaded native dialog and solid keyboard support cover most portfolios, blogs and documentation sites.
Build it, then open the Network tab and prove it costs nothing until someone presses Ctrl+K. That's the difference between a feature that adds polish and one that adds weight.
