DEV Community

Gissur Runarsson
Gissur Runarsson

Posted on

How to Use ImportKit: Add CSV/Excel Import to Your React App in 10 Minutes

Ever spent weeks building CSV import functionality only to realize you still need Excel support, better error handling, and a column mapping UI that doesn't confuse users? ImportKit solves this with a drop-in React component that handles everything from file parsing to AI-powered column matching. Here's how to integrate it in one afternoon.

How to Use ImportKit: Add CSV/Excel Import to Your React App in 10 Minutes

Building CSV import functionality from scratch takes weeks. You need file parsing, column mapping UI, validation logic, error handling, and Excel support. ImportKit gives you all of this as a React component you can drop into your app in one afternoon.

This guide walks through integrating ImportKit for a common scenario: letting users import contact lists into a CRM application.

Prerequisites

You need:

  • A React 18.x or React 19.x application
  • An ImportKit account (sign up at importkit.app)
  • 10 minutes

ImportKit supports both React 18 and React 19 as peer dependencies, so it works with any modern React setup including Next.js applications.

Step 1: Install the Package

ImportKit is published as @importkit/react on npm. The package is MIT licensed and includes TypeScript type definitions.

npm install @importkit/react
Enter fullscreen mode Exit fullscreen mode

The package provides dual ESM/CJS builds via tsup, so it works with both modern and legacy bundler configurations.

Step 2: Get Your API Key

Log into the ImportKit dashboard and navigate to the API Keys section. Generate a new key for your application. The widget requires an API key for authentication and usage tracking. Keys are scoped per user and can be revoked from the dashboard.

The free tier gives you 500 rows per month, which resets automatically on the 1st via Supabase pg_cron. Paid tiers offer 5,000 rows (Starter), 50,000 rows (Pro), or unlimited (Enterprise).

Step 3: Define Your Data Schema

ImportKit uses a field configuration to define what data you expect. For a contact import, you might have:

const contactFields = [
  {
    name: 'email',
    label: 'Email Address',
    type: 'email',
    required: true
  },
  {
    name: 'firstName',
    label: 'First Name',
    type: 'text',
    required: true
  },
  {
    name: 'lastName',
    label: 'Last Name',
    type: 'text',
    required: false
  },
  {
    name: 'status',
    label: 'Status',
    type: 'enum',
    enum: {
      values: ['Active', 'Inactive', 'Pending'],
      hints: ['enabled,live', 'disabled,off', 'waiting,review']
    }
  },
  {
    name: 'age',
    label: 'Age',
    type: 'number',
    validate: [
      {
        type: 'min',
        value: 0,
        message: 'Age must be positive'
      }
    ]
  }
]
Enter fullscreen mode Exit fullscreen mode

ImportKit supports five field types: text, email, number, date, and enum. Each type can have custom validation rules including email format checking, numeric ranges, string length constraints, and regex patterns.

The enum field type is particularly powerful. It uses a 6-step matching cascade to handle messy real-world data: exact match, case-insensitive match, customer-specific learned mappings, global learned mappings, developer-provided hints, and finally AI semantic matching. This means "Administrator" automatically maps to "Admin" and "enabled" maps to "Active" using the hints you provide.

Step 4: Add the Widget to Your Component

import { ImportWidget } from '@importkit/react'

function ContactImportPage() {
  const handleComplete = (data) => {
    console.log('Imported contacts:', data)
    // Send to your API
    fetch('/api/contacts/bulk', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: { 'Content-Type': 'application/json' }
    })
  }

  return (
    <div>
      <h1>Import Contacts</h1>
      <ImportWidget
        apiKey="your-api-key"
        fields={contactFields}
        onComplete={handleComplete}
      />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

The widget handles everything: drag-and-drop file upload, parsing CSV and Excel files (.csv, .xlsx, .xls), column mapping, validation, and error correction. Users see a multi-step interface that guides them through the import process.

Step 5: Let AI Handle Column Mapping

When a user uploads a file, ImportKit sends the CSV headers and your target fields to /api/suggest-mapping. This endpoint calls OpenAI gpt-4o-mini with temperature=0 for deterministic results. The AI returns structured JSON via the response_format parameter with confidence scores for each mapping suggestion.

If AI fails or is unavailable, the widget falls back to substring matching automatically. This means your imports work even if OpenAI is down. Users see immediate substring matching while the AI loads asynchronously in the background.

For example, if the CSV has columns "E-mail", "First", "Last", "Account Status", the AI maps:

  • "E-mail" → email (95% confidence)
  • "First" → firstName (90% confidence)
  • "Last" → lastName (90% confidence)
  • "Account Status" → status (85% confidence)

Users can override any mapping manually if the AI gets it wrong.

Step 6: Validate Before Import

ImportKit validates every row against your rules in real-time. The validation shows inline errors per row in the preview step. Users can choose to import only valid rows or fix errors before importing.

Validation rules support email format checking, numeric ranges (min/max), string length constraints (minLength/maxLength), regex patterns, and enum value matching. Required fields block the entire import if missing.

This catches data quality issues before they enter your system and reduces support tickets from bad imports.

Optional: Use Templates for Reusable Configs

If you have multiple import scenarios or want to let users manage imports themselves, save your field configuration as a template in the dashboard.

Templates are stored in Supabase's import_templates table and loaded via the widget's templateId prop:

<ImportWidget
  apiKey="your-api-key"
  templateId="template-uuid"
  onComplete={handleComplete}
/>
Enter fullscreen mode Exit fullscreen mode

This enables consistent imports across users and sessions while reducing implementation time. Non-technical users can manage import configurations through the dashboard CRUD UI.

Optional: Customize the Appearance

ImportKit supports full theming to match your brand. You can customize colors, borders, fonts, and remove the "Powered by ImportKit" branding:

<ImportWidget
  apiKey="your-api-key"
  fields={contactFields}
  onComplete={handleComplete}
  theme={{
    primaryColor: '#6366f1',
    borderRadius: '12px',
    fontFamily: 'Inter'
  }}
  showBranding={false}
/>
Enter fullscreen mode Exit fullscreen mode

The showBranding prop defaults to true. Setting it to false removes the "Powered by ImportKit" footer for a white-label experience.

Optional: Set Up Webhook Delivery

If you're on the Pro or Enterprise tier, configure a webhook URL in the dashboard to receive import data automatically. ImportKit POSTs the data to your endpoint after each import completes.

Webhooks include an X-ImportKit-Signature header with an HMAC-SHA256 signature for verification. The secret is generated via crypto.randomBytes(32). Recipients verify by computing HMAC of the request body.

Delivery retries 3 times with exponential backoff (1 second, 4 seconds delays) and a 10-second timeout per attempt. Each webhook payload includes:

{
  "event": "import.completed",
  "importId": "uuid",
  "rowCount": 150,
  "templateName": "Contact Import",
  "timestamp": "2024-01-28T10:30:00Z"
}
Enter fullscreen mode Exit fullscreen mode

This enables automated workflows without polling. If all retry attempts fail, the delivery is logged but does not block the import response. Webhooks are fire-and-forget from the user's perspective.

What Happens Behind the Scenes

ImportKit uses PapaParse for CSV parsing and SheetJS (xlsx library) for Excel parsing. It automatically extracts headers and data from uploaded files. The widget reads the first sheet by default from Excel files and converts to JSON for mapping.

All authentication happens via API key in the request body, not cookies. This uses supabaseAdmin to bypass Row Level Security (RLS) for API key validation. The widget works from any domain without CORS issues since the API routes are configured with appropriate CORS headers.

Usage tracking happens through the /api/track-import endpoint, which checks rows_used_this_month against tier limits before recording an import. If you exceed your limit, you get an error until the automatic reset on the 1st.

When to Use ImportKit vs Building It Yourself

ImportKit replaces weeks of development time with a single npm package. You avoid building parsing logic, validation UI, mapping interfaces, error handling, retry logic, and Excel support from scratch.

Compare this to DIY solutions:

  • ImportKit provides AI-powered column matching vs manual substring matching
  • Built-in error handling and retry logic for webhooks vs implementing your own
  • Handles both CSV and Excel formats out of the box vs separate parsers
  • Maintained and updated by the ImportKit team vs your maintenance burden

The widget is open source (MIT licensed) with code published at github.com/gthorr/importkit. The dashboard and backend are part of the hosted service.


For implementation questions, check the GitHub repository or the documentation at importkit.app.

Top comments (0)