Next.js

Data Export

Exporting structured data to a CSV file dynamically from an API route.

CSV Export API: A route handler that formats JSON data into CSV and sets headers to trigger a file download.
📄app/api/export/route.ts
TS
import { NextResponse } from 'next/server';

export async function GET() {
  const users = [
    { id: 1, name: 'Alice', email: 'alice@example.com' },
    { id: 2, name: 'Bob', email: 'bob@example.com' }
  ];

  // Convert JSON to CSV string
  const csvHeaders = 'ID,Name,Email\n';
  const csvRows = users.map(u => `${u.id},${u.name},${u.email}`).join('\n');
  const csvString = csvHeaders + csvRows;

  // Return as a downloadable CSV file
  return new NextResponse(csvString, {
    headers: {
      'Content-Type': 'text/csv',
      'Content-Disposition': 'attachment; filename="users-export.csv"',
    },
  });
}