# Next.js search app

A search page with a popularity cut and a source picker, rendered on the server so the key never reaches the browser.

Available · TypeScript, Next.js 16 · Three files · Key stays on the server · Tested 2026-11-19

> **For agents.** Read the API key from the `MILLIONSHORT_API_KEY` environment variable. Never print it; where a client needs it in a settings file, use a file that is not committed.
> The MCP address is https://mcp.millionshort.com/mcp (streamable HTTP; send `Authorization: Bearer <key>`, or no header for the no-key mode).
> On `INSUFFICIENT_CREDITS` stop and ask a person; on `RATE_LIMITED` or `CAPACITY` wait the `Retry-After` seconds, then retry once.
> Set-up steps written for agents: https://millionshort.com/docs/auth.md. Every integration: https://millionshort.com/docs/integrations.md.

The page is a server component: the form submits with a plain GET, the server calls `POST /v1/search` with the key from its environment, and the browser receives finished HTML. There is no client JavaScript of ours, and no route a visitor could call to use your key for other searches.

## 1. Get the code

Four files: `package.json`, `lib/millionshort.ts`, `app/page.tsx` and `app/layout.tsx`.

```json package.json
{
  "name": "millionshort-nextjs-search",
  "private": true,
  "description": "A search page on MillionShort: Next.js, the key kept on the server.",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^16.4.6",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "server-only": "^0.0.1"
  },
  "devDependencies": {
    "@types/node": "^26.6.6",
    "@types/react": "^19.3.0",
    "typescript": "^7.0.2"
  }
}
```

```ts lib/millionshort.ts
// The one place the key is read. `server-only` makes the build fail if a client component ever
// imports this module, so the key cannot reach the browser.
import 'server-only';

const API = (process.env.MILLIONSHORT_BASE_URL ?? 'https://api.millionshort.com').replace(/\/$/, '');

export type Result = {
  position: number;
  title: string;
  url: string;
  site: string;
  snippet: string | null;
  published_date: string | null;
  popularity: { rank: number | null; bucket: string };
};

export async function search(query: string, removeTopSites: number, source: string): Promise<{ results: Result[]; credits: number }> {
  const res = await fetch(`${API}/v1/search`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, sources: [source], remove_top_sites: removeTopSites, num_results: 10 }),
    cache: 'no-store',
  });
  const body = (await res.json()) as { data?: { results: Result[] }; usage?: { credits: number }; error?: { code: string; message: string } };
  if (!res.ok || !body.data) throw new Error(`${body.error?.code ?? res.status}: ${body.error?.message ?? 'search failed'}`);
  return { results: body.data.results, credits: body.usage?.credits ?? 0 };
}
```

```tsx app/page.tsx
// Anyone who can open this page searches with your key: put it behind your own sign-in, or a rate
// limit, before you make it public.
import { search } from '../lib/millionshort';

const CUTS = [
  ['0', 'All sites'],
  ['1000', 'Without the top 1,000'],
  ['10000', 'Without the top 10,000'],
  ['100000', 'Without the top 100,000'],
];
const SOURCES = ['web', 'news', 'discussions', 'academic'];

export default async function Page({ searchParams }: { searchParams: Promise<{ q?: string; cut?: string; source?: string }> }) {
  const { q = '', cut = '1000', source = 'web' } = await searchParams;
  let answer: Awaited<ReturnType<typeof search>> | null = null;
  let problem = '';
  if (q.trim()) {
    try {
      answer = await search(q.trim(), Number(cut) || 0, SOURCES.includes(source) ? source : 'web');
    } catch (error) {
      // the API's error code and message (a missing key, no credits left, too many searches a minute)
      problem = error instanceof Error ? error.message : 'search failed';
    }
  }
  return (
    <main style={{ maxWidth: 720, margin: '40px auto', padding: '0 16px', fontFamily: 'system-ui, sans-serif' }}>
      <h1>Search</h1>
      <form style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <input name="q" defaultValue={q} placeholder="Search the long tail" style={{ flex: 1, minWidth: 240 }} />
        <select name="cut" defaultValue={cut}>
          {CUTS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
        </select>
        <select name="source" defaultValue={source}>
          {SOURCES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
        <button type="submit">Search</button>
      </form>
      {problem && <p role="alert" style={{ color: '#a00' }}>The search did not work: {problem}</p>}
      {answer && (
        <>
          <ol>
            {answer.results.map((r) => (
              <li key={r.url} style={{ margin: '16px 0' }}>
                <a href={r.url}>{r.title}</a>
                <div style={{ color: '#666', fontSize: 13 }}>{r.site} · {r.popularity.bucket}{r.published_date ? ` · ${r.published_date}` : ''}</div>
                {r.snippet && <p style={{ margin: '4px 0' }}>{r.snippet}</p>}
              </li>
            ))}
          </ol>
          <p style={{ color: '#666', fontSize: 13 }}>{answer.results.length} results, {answer.credits} credit(s).</p>
        </>
      )}
    </main>
  );
}
```

```tsx app/layout.tsx
import type { ReactNode } from 'react';

export const metadata = { title: 'Search', description: 'A search page on MillionShort.' };

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
```

## 2. Run it

```bash
npm install
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
npm run dev
```

Open the address `next dev` prints, and search. To deploy, set `MILLIONSHORT_API_KEY` as a server-side environment variable of your host; nothing else is needed.

## 3. What you get

A form, then ten results with each site's popularity band and date. The cut defaults to "Without the top 1,000"; the source picker switches between `web`, `news`, `discussions` and `academic`. The page says what the search cost, and when a search fails it says why (the API's error code), rather than showing an error page.

## 4. Change it

| To | Change |
|---|---|
| Offer more sources | Add them to `SOURCES` (each searched source costs 1 credit) |
| Show passages, not snippets | Add `max_highlights: 2` to the body and render `highlights` |
| Let a model answer too | Call a model with the results on the server, as in [RAG with fresh pages](https://millionshort.com/docs/integrations/cookbook-rag-fresh-pages) |

## Costs and limits

1 credit per search. Anyone who can open the page can search with your key: put the page behind your own sign-in, or add a rate limit, before you make it public.

## When it fails

| What you see | Why | Fix |
|---|---|---|
| `401 AUTH_MISSING_KEY` or `AUTH_INVALID_KEY` | The key is missing or wrong | Set `MILLIONSHORT_API_KEY`; keys start with `ms-` |
| `400 INVALID_PARAM` | A field name or value the API does not take | The `message` names the field; the [search reference](https://millionshort.com/docs/search/parameters) lists them all |
| `429 RATE_LIMITED` or `CAPACITY` | Too many calls a minute, or no free capacity right now | Wait the `Retry-After` seconds, then retry |
| `429 INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; do not retry |
| "The search did not work: `AUTH_MISSING_KEY`" after deploying | The key is not set on the host | Set `MILLIONSHORT_API_KEY` in the host's server environment, not as a public variable |
| The build fails on `server-only` | A client component imports `lib/millionshort.ts` | Keep the search in server code: that error is what keeps the key out of the browser |

## Related

- [Vercel AI SDK](https://millionshort.com/docs/integrations/vercel-ai-sdk): search as a tool for a model in the same kind of app.
- [Search reference](https://millionshort.com/docs/search/parameters): every field the body can take.
