Content-Type for CSV File Downloads
Set the Content-Type header for serving or sending CSV files. Covers text/csv charset, Content-Disposition, and Excel compatibility.
Detailed Explanation
CSV Content-Type
CSV (Comma-Separated Values) files use the text/csv media type. Proper charset declaration is critical for non-ASCII data.
The Header Value
Content-Type: text/csv; charset=utf-8
Header Parameter
The header parameter indicates whether the first row contains column names:
Content-Type: text/csv; charset=utf-8; header=present
Values: present or absent.
Triggering Download
To make the browser download the CSV rather than display it:
Content-Type: text/csv; charset=utf-8
Content-Disposition: attachment; filename="export-2025-01.csv"
Excel Compatibility
Microsoft Excel may not correctly detect UTF-8 encoding. To ensure compatibility, prepend a UTF-8 BOM (Byte Order Mark) to the CSV content:
const BOM = "\uFEFF";
const csvContent = BOM + "Name,Email\nJohn,john@example.com";
Alternative: Tab-Separated Values
For tab-separated files, use:
Content-Type: text/tab-separated-values; charset=utf-8
curl Example
# Download a CSV export
curl -H "Accept: text/csv" \
-o report.csv \
https://api.example.com/reports/monthly.csv
fetch() Response Handling
const response = await fetch("/api/export.csv");
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "export.csv";
a.click();
Use Case
Use this when serving CSV exports from APIs, building data export features, or integrating with spreadsheet applications. Common in reporting dashboards, analytics platforms, and data pipeline endpoints.