# CSV import

> Contacts → Import, done properly: your file's columns thread themselves to your fields, bad cells become fields you fix in place, and the rows go to your server in batches.

CSV imports usually fail at the end, with "row 1,284 is invalid" and nothing to do about it. Here the file is read in the browser in slices, so even a big one never freezes the page. Its columns line up against your fields and the ones that match by name are already threaded together; carry a column onto a field to change it, or pick it from the field's own dropdown, which grows out of its pill. Before anything is sent, every row is checked: "2,996 ready · 4 need a look", and the rows with problems open with their bad cells as fields. Fix one and it says so and folds away while the counts roll, or skip what's left. Rows then go to onImport in batches, the bar filling and "1,250 of 2,996" rolling, and Cancel stops after the batch in flight. At the end a ring and a check draw, and anything skipped or refused downloads as a CSV with the reason on each row.

## Install

```bash
npx shadcn@latest add @hairline/csv-import
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`, `status-button`
- Docs and live preview: https://hairlineui.com/ui/csv-import
- Registry item (source): https://hairlineui.com/r/csv-import.json

## Usage

```tsx
import { CsvImport } from "@/components/csv-import";

<CsvImport
  noun={{ one: "contact", many: "contacts" }}
  fields={[
    { key: "name", label: "Name", required: true },
    { key: "email", label: "Email", required: true, match: ["e-mail"] },
  ]}
  onImport={(rows, { signal }) => api.importContacts(rows, { signal })}
/>
```

## Batches into Postgres through a route

Each batch is one request; the route validates again on the server (never trust the browser), inserts what it can in one statement, and returns the rows it refused by their index in the batch. Those come back in the skipped file with your reason. With Supabase or D1, the route is a single bulk insert the same way.

```tsx
// app/api/contacts/import/route.ts
import { z } from "zod";
import { db } from "@/lib/db";

const Row = z.object({ name: z.string().min(1), email: z.string().email(), company: z.string().optional(), plan: z.string().optional() });

export async function POST(req: Request) {
  const user = await requireUser(req);
  const rows: unknown[] = await req.json();
  const failed: { index: number; reason: string }[] = [];
  const good = rows.flatMap((r, index) => {
    const parsed = Row.safeParse(r);
    if (!parsed.success) {
      failed.push({ index, reason: parsed.error.issues[0].message });
      return [];
    }
    return [{ ...parsed.data, workspaceId: user.workspaceId, index }];
  });
  const existing = await db.contact.findMany({ where: { workspaceId: user.workspaceId, email: { in: good.map((g) => g.email) } }, select: { email: true } });
  const taken = new Set(existing.map((e) => e.email));
  for (const g of good) if (taken.has(g.email)) failed.push({ index: g.index, reason: "Already a contact." });
  await db.contact.createMany({ data: good.filter((g) => !taken.has(g.email)).map(({ index, ...c }) => c) });
  return Response.json({ failed });
}

// app/contacts/import.tsx
"use client";
<CsvImport
  title="Import contacts"
  noun={{ one: "contact", many: "contacts" }}
  fields={fields}
  templateHref="/templates/contacts.csv"
  onImport={async (rows, { signal }) => {
    const res = await fetch("/api/contacts/import", { method: "POST", body: JSON.stringify(rows), signal });
    if (!res.ok) throw new Error("The server didn't take this batch.");
    return res.json();
  }}
  onDone={({ imported }) => imported && router.refresh()}
/>
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `fields` | `CsvField[]` | – | { key, label, required?, match?, validate? }. match lists other column names to recognise; validate returns why a value won't do. |
| `onImport` | `(rows, { signal, start }) => Promise<{ failed? } \| void>` | – | Saves one batch of rows shaped { [key]: value }. Return failed: [{ index, reason }] for rows your server refused; throw to mark the whole batch skipped. |
| `batchSize` | `number` | `250` | Rows per onImport call. |
| `maxRows` | `number` | `50000` | Files with more rows are refused before matching. |
| `noun` | `{ one, many }` | `{ one: "row", many: "rows" }` | What a row is, for the counts and buttons. |
| `templateHref` | `string` | – | A "Download a template" link under the drop target. |
| `title` | `string` | `"Import"` | The card's heading. |
| `description` | `string` | – | The line under the heading. |
| `onDone` | `({ imported, skipped, cancelled }) => void` | – | After the last batch, e.g. to refresh the list behind it. |
| `ref` | `Ref<CsvImportHandle>` | – | load(text, name?) reads text as if it were a dropped file, e.g. from a paste or a sample. |

## States

- **drop**: Dragging a file over the target turns its edge blue and lifts the icon 4px with a slight overshoot; the line morphs to "Drop to read it". A file that isn't CSV, is empty or is over maxRows shakes the target and says why.
- **read**: The file is parsed in 200,000-character slices with a pause between (200,000 rows take about a quarter of a second), the icon spinning. The separator is taken from the first line.
- **match**: Steps slide in 28px from the right while the card eases to its height. Columns that match a field by name, ignoring case and punctuation ("E-mail address" → Email), are threaded on arrival; each thread draws itself in 520ms. Carrying a column trails a dashed thread and lights the field under the pointer. Each field's pill grows into the list of columns, a sample under every name; narrow cards show only the fields and their pills.
- **review**: Every row is checked (required fields, then validate). The ready and need-a-look counts roll. Rows with problems show their bad cells as inputs with a red hairline and the reason; when a row is right its badge morphs to Fixed, and 650ms later it folds away.
- **import**: Ready rows go to onImport in batches of batchSize. The bar fills by transform; the count rolls. Cancel aborts the signal and stops after the batch in flight. A batch that throws marks its rows as skipped with the error's message.
- **done**: A ring draws in 640ms, then a check. If anything was skipped or refused, "Skipped rows" downloads them as CSV with a column saying why.

## What it handles

CSV imports usually fail at the end with “row 1,284 is invalid” and nothing to do about it. This reads the file in the browser, matches the columns, checks every row first and lets people fix problems before anything is sent.

- **Big files don’t freeze the page**: The file is read in slices with a pause between them. 200,000 rows take about a quarter of a second.
- **Columns match themselves**: Columns that match a field by name, ignoring case and punctuation, are already threaded. Carry a column onto a field, or use its dropdown, to change it.
- **Checked before anything is sent**: Every row is checked first, and the counts read like “2,996 ready · 4 need a look”.
- **Fix problems in place**: Rows with problems open with their bad cells as fields. Fix one and it folds away, or skip what is left.
- **Sent in batches**: Rows go to your onImport function in batches with a progress bar. Cancel stops after the batch in flight.
- **Skipped rows come back as a CSV**: Anything skipped or refused downloads as a file with the reason on each row.

## Replaces

a CSV parser, a column mapping screen, row validation, a batch upload loop, a progress bar, an errors download

## Where it fits

- **CRM and contacts**: Import contacts from a spreadsheet exported by another tool.
- **Product catalogues and inventory**: Bring in thousands of products with their prices and stock.
- **Onboarding**: Let new customers move their data in from the tool they used before.
- **Admin tools**: Add many users, members or records at once.

## Notes

- The drop target is the label of a real file input: Tab reaches it, Enter or Space opens the picker, and its focus ring shows on the target.
- Matching works without a pointer: every field's pill opens a listbox (arrows, typing a name, Enter), and clicking a column then a field matches them too. Threads are drawn for the eye; screen readers hear the pills.
- Problem cells are real inputs marked aria-invalid with their reason under them. The import bar is a progressbar with the row counts as its values. Each step's result is announced in a status region.
- Nothing leaves the browser until onImport: parsing, matching and checking all happen on the page.
- Reduced motion swaps steps in place and draws threads and checks at once.

License: MIT (https://hairlineui.com/license#components)
