I have a simple array of data I would like to export as CSV using a NextJS api route. So I tried this:
import { captureException } from '@sentry/nextjs';
import { NextResponse } from 'next/server';
import { parse } from 'json2csv';
export const fetchCache = 'force-no-store';
export const revalidate = 0;
export const dynamic = 'force-dynamic';
export async function GET(req: Request) {
const { emailEventId, token } = await req.json();
try {
// Fetch or generate your data here. Example:
const data = [
{ id: 1, name: 'Alice', email: '[email protected]' },
{ id: 2, name: 'Bob', email: '[email protected]' }
];
const csv = parse(data, { fields: ['id', 'name', 'email'] });
return new Response(csv, {
status: 200,
headers: {
'Content-Type': `text/csv`,
'Content-Disposition': `attachment; filename="export.csv"`,
},
})
} catch (error) {
captureException(error);
return NextResponse.json({});
}
}
But it results in this: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
Any ideas how to export a csv from a nextjs 13 api route?