Files

CSV

How to define, write and query CSV data.

Define Collection

content.config.ts
import { defineCollection, defineContentConfig, z } from '@nuxt/content'

export default defineContentConfig({
  collections: {
    authors: defineCollection({
      type: 'data',
      source: 'authors/**.csv',
      schema: z.object({
        name: z.string(),
        email: z.string(),
        avatar: z.string()
      })
    })
  }
})

Create .csv files

Create author files in content/authors/ directory.

id,name,email
1,John Doe,john@example.com
2,Jane Smith,jane@example.com
3,Alice Johnson,alice@example.com
Each CSV file should have a header row that defines the column names, which will be used as object keys when parsed.

Query Data

Now we can query authors:

<script lang="ts" setup>
// Find a single author
const { data: author } = await useAsyncData('john-doe', () => {
  return queryCollection('authors')
    .where('name', '=', 'John Doe')
    .first()
})

// Get all authors
const { data: authors } = await useAsyncData('authors', () => {
  return queryCollection('authors')
    .order('name', 'ASC')
    .all()
})
</script>

<template>
  <ul>
    <li v-for="author in authors" :key="author.id">
      {{ author.name }} ({{ author.email }})
    </li>
  </ul>
</template>

Configuration

You can configure how CSV files are parsed in your nuxt.config.ts:

nuxt.config.ts
export default defineNuxtConfig({
  content: {
    build: {
      csv: {
        // Convert CSV data to JSON objects
        json: true,
        // Specify custom delimiter (default is ',')
        delimiter: ','
      }
    }
  }
})

With json: true in the configuration, each row will be converted to a JavaScript object with the header row used as keys:

[
  {
    "id": "1",
    "name": "John Doe",
    "email": "john@example.com"
  },
  {
    "id": "2",
    "name": "Jane Smith",
    "email": "jane@example.com"
  }
]

Custom Delimiters

If your CSV files use a different delimiter, you can specify it in the configuration:

nuxt.config.ts
export default defineNuxtConfig({
  content: {
    build: {
      csv: {
        delimiter: ';' // Use semicolon as delimiter
      }
    }
  }
})

This would parse CSV files like:

semicolon-data.csv
id;name;email
1;John Doe;john@example.com
2;Jane Smith;jane@example.com
The CSV parser can be disabled by setting csv: false in the configuration if you don't need CSV support.