How to import CSV files in Encore.dev

6 min read
Learn how to build a CSV import feature in Encore.dev. Step-by-step guide for developers integrating spreadsheet uploads in SaaS applications.

How to Import CSV Files in Encore.dev Using CSVBox

Adding CSV import functionality is a common requirement for SaaS apps and internal tools—onboarding customer data, configuring settings from spreadsheets, or seeding databases. If you’re building with Encore.dev (a type-safe backend framework in Go), this guide shows a practical, production-oriented way to add CSV support using CSVBox, a plug-and-play uploader that handles the UI, client-side parsing, mapping, and cleaned JSON delivery.

This step-by-step tutorial is ideal for:

  • Full-stack developers building on Encore.dev
  • SaaS product and engineering teams shipping CSV-based onboarding
  • Engineers who want a secure, validated, embeddable CSV import flow

Note: small freshness tip — this guide includes best practices relevant in 2026 for building reliable CSV import pipelines.


Why add CSV upload to your Encore.dev backend?

Encore gives you fast, type-safe cloud services in Go, but you’ll typically want a complete CSV import flow that includes:

  • Client-side parsing and column mapping
  • An embeddable upload UX for non-technical users
  • Schema-driven validation and user feedback
  • Clean JSON delivery to your backend via webhooks

CSVBox provides an embeddable widget, mapping UI, validation rules, and webhook delivery so you can keep backend logic focused on verification, storage, and downstream processing rather than building CSV tooling from scratch.

Common SaaS use cases:

  • Importing user or customer accounts from a spreadsheet
  • Uploading product inventory or pricing updates
  • Bulk updating employee records or settings via admin UI

Integration overview: CSV upload in 5 steps

High-level flow (file → map → validate → submit → process):

  1. Create an importer in CSVBox and define expected columns and validation rules.
  2. Embed the CSVBox widget in your frontend (React, Vue, or plain JS).
  3. Create an HTTP webhook endpoint in your Encore app to receive cleaned JSON.
  4. Configure the CSVBox importer to POST to your Encore webhook.
  5. Validate, store, and/or queue each row in your backend.

Below are practical examples and tips for each step.


Step 1: Create a CSV importer in CSVBox

In the CSVBox dashboard:

  • Create a free account and add a new importer.
  • Define expected columns (for example: Name, Email, Role).
  • Add validation rules (required fields, type checks, regex patterns).
  • Optionally customize mapping instructions and user-facing help text.

Keep these items handy after creation:

  • Importer ID
  • Client Key (or client_id) for embedding the widget

You’ll use those identifiers in your frontend integration.


Step 2: Embed the CSVBox widget in your frontend

CSVBox provides a small JS widget you can embed. Example HTML + JS integration:

<script src="https://js.csvbox.io/widget.js"></script>
<button id="csv_upload_button">Import CSV</button>

<script>
  document.getElementById('csv_upload_button').addEventListener('click', function () {
    CSVBox.init({
      client_id: 'your-client-id',
      importer_id: 'your-importer-id',
      user_id: 'current-user-id',
      metadata: {
        team_id: 'abc123'
      }
    });
  });
</script>

This launches a modal with file selection, preview, mapping, and validation. You can wire user_id and metadata to associate uploads with your users or teams.

Embed patterns for React or Vue typically call CSVBox.init from a component event handler. Style your trigger to match your product UI.


Step 3: Handle CSVBox webhooks in Encore.dev

CSVBox posts cleaned JSON to a webhook URL you define. Your Encore HTTP handler should decode the JSON payload, validate fields server-side, and insert or enqueue rows for processing.

Example Go handler (basic pattern):

package importer

import (
  "context"
  "encoding/json"
  "net/http"
  "encore.dev/storage/sqldb"
)

// Struct for uploaded row
type ImportRow struct {
  Name  string `json:"Name"`
  Email string `json:"Email"`
  Role  string `json:"Role"`
}

// HTTP webhook handler
func ImportWebhook(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  var payload struct {
    ImportID   string      `json:"import_id"`
    ImporterID string      `json:"importer_id"`
    UserID     string      `json:"user_id"`
    Rows       []ImportRow `json:"data"`
  }

  if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
    http.Error(w, "Invalid JSON", http.StatusBadRequest)
    return
  }

  for _, row := range payload.Rows {
    if err := saveRow(row); err != nil {
      http.Error(w, "Failed to store row", http.StatusInternalServerError)
      return
    }
  }

  w.WriteHeader(http.StatusOK)
}

// Save each row to your DB
func saveRow(row ImportRow) error {
  _, err := sqldb.Exec(
    `INSERT INTO users (name, email, role) VALUES ($1, $2, $3)`,
    row.Name, row.Email, row.Role,
  )
  return err
}

// Register endpoint in Encore (see Encore docs for the current pattern to expose an HTTP handler)
var _ = encore.NewHTTPHandler("/api/import-callback", ImportWebhook, encore.HTTPConfig{
  Method: "POST",
})

Notes:

  • Treat field names as case-sensitive when mapping JSON to Go structs; use json struct tags that match your CSVBox column names.
  • Perform server-side validation (unique constraints, format checks) even if CSVBox validates client-side.
  • Consider batch writes or transactions for atomicity and performance.

In the CSVBox dashboard:

  1. Edit your importer.

  2. Go to Settings → Webhooks.

  3. Set the success webhook URL to your Encore endpoint, for example:

    https://.encore.dev/api/import-callback

After a successful import and mapping, CSVBox will POST the cleaned JSON payload to this URL.

Tip (security): Require a shared secret, token, or other verification on the webhook requests, and validate it server-side before trusting the payload.


Step 5: Customize processing and storage

Once you receive rows:

  • Run server-side validation and uniqueness checks (e.g., emails).
  • Use SQL transactions for multi-table inserts.
  • Queue background jobs for slow tasks (sending emails, creating related records).
  • Record import metadata (import_id, user_id) for auditing and retrying failed rows.
  • Emit structured logs for observability; Encore supports logging helpers.

Example logging pattern:

log.Info("Imported user", "email", row.Email)

CSVBox payload format (reference)

Example webhook payload structure:

{
  "import_id": "abc123",
  "importer_id": "xyz987",
  "user_id": "u001",
  "data": [
    {
      "Name": "Alice",
      "Email": "alice@example.com",
      "Role": "Admin"
    },
    {
      "Name": "Bob",
      "Email": "bob@example.com",
      "Role": "User"
    }
  ]
}

Map JSON fields to your Go structs with matching json tags. Customize column mapping inside CSVBox so your field names align with your backend model.


Common issues & fixes

Webhook not triggering?

  • Verify the webhook URL is correct in CSVBox.
  • Ensure your Encore endpoint is deployed and reachable from the public internet.
  • Tail logs or use a request inspector to see incoming requests during testing.

JSON parsing errors?

  • Column names are case-sensitive; confirm CSVBox mapping and Go struct tags match.
  • Inspect the raw webhook body to confirm expected structure.

Database insert failures?

  • Sanitize and validate input before writes.
  • Use database constraints and handle unique/constraint errors gracefully.
  • Wrap multi-row inserts in transactions when needed.

Environment separation?

  • Create separate importers in CSVBox for dev and prod, each pointing to different webhook endpoints.

Why use CSVBox with Encore.dev (short summary)

Use CSVBox to handle the front-end CSV experience (file → map → validate → submit) and Encore.dev to handle secure, typed backend processing. This split keeps front-end UX concerns out of your backend and enables fast integrations with minimal boilerplate.

Benefits:

  • Interactive mapping and validation for end users
  • Clean JSON webhook delivery to your backend
  • Reduced front-end parsing complexity
  • Faster developer iteration and fewer edge-case parsing bugs

With this approach you get a developer-friendly, auditable CSV import pipeline that’s easy to extend and maintain in 2026.


Next steps & best practices

  • Validate webhook authenticity (shared secret or token).
  • Associate imports with user sessions or team identifiers (metadata).
  • Track import status and per-row errors in your DB for retries and auditing.
  • Use background jobs or worker queues for large imports.
  • Monitor logs and set alerts for webhook failures or high error rates.

Full CSVBox docs: https://help.csvbox.io/
Encore API reference: https://encore.dev/docs/reference

Importing CSVs doesn’t have to be painful. Combining CSVBox’s embeddable import UX with Encore.dev’s type-safe backend gives you a robust, low-maintenance CSV onboarding flow.

Happy shipping! ✅


Related keywords: csv import in Go, encore.dev webhook, spreadsheet upload for SaaS, csv file upload for backend developers, csvbox integration, importing data securely in Go apps, bulk inserts from CSV, encore csv tutorial

Canonical URL: https://help.csvbox.io/getting-started/2.-install-code

Related Posts