NextJS throwing 500 when trying to download a file
Unanswered
French Bulldog posted this in #help-forum
French BulldogOP
I've setup a file download route, here's the code :
For some reason it's throwing a 500 error in the browser (and any API client) but isn't showing anything in the terminal.
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
try {
const { id } = params;
const file = await getFile(id);
if (!file) {
return NextResponse.json({ error: 'File not found' }, { status: 404 });
}
if (file.protected) {
const user = await getOptionalUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const hasPermission = await checkPermissions({
user,
permissions: [
{ action: 'rw', resource: 'file', resourceId: id },
{ action: 'r', resource: 'file', resourceId: id },
{ action: 'rw', resource: 'file' },
{ action: 'r', resource: 'file' },
],
either: true,
});
if (!hasPermission) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
}
const storageDir = getEnv('FILE_STORAGE_PATH', './tmp/file_storage');
const filePath = join(storageDir, id);
const fileBuffer = await readFile(filePath);
return new NextResponse(fileBuffer as unknown as BodyInit, {
headers: {
'Content-Type': file.fileType || 'application/octet-stream',
'Content-Disposition': `attachment; filename="${file.id}"`,
'Content-Length': file.size.toString(),
},
});
} catch (error) {
console.error('File download error:', error);
return NextResponse.json(
{
error: error instanceof Error ? error.message : 'Failed to download file',
},
{ status: 500 },
);
}
}
For some reason it's throwing a 500 error in the browser (and any API client) but isn't showing anything in the terminal.
1 Reply
French BulldogOP
The content was too long so cut the head off, here are the import statements
import { NextRequest, NextResponse } from 'next/server';
import { getFile } from '@/app/actions/files';
import { getOptionalUser } from '@/lib/dal/session';
import { checkPermissions } from '@/lib/dal/permissions';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { getEnv } from '@/core/env';