Return file using NextResponse
Answered
Giant panda posted this in #help-forum
Giant pandaOP
I'm trying to secure certain images behind an API but don't know how to properly return a file buffer using the new NextResponse object. Here's what I've tried so far:
When I call the API, the image is just the generic missing file icon, even though the buffer seems to be entirely there and the status is 200:
export async function GET(
_: NextRequest,
{ params: { filePath } }: { params: DynamicRouteParams },
) {
// const session = await auth();
// if (!session) return NextResponse.json(null, { status: 401 });
const resolvedPath = path.resolve(`private/${filePath.join("/")}`);
if (!existsSync(resolvedPath)) return NextResponse.json(null, { status: 404 });
const file = await readFile(resolvedPath);
const headers = new Headers();
headers.set("Cache-Control", "private, max-age=43200"); // Cache content for 12 hours
headers.set("Content-Length", file.byteLength.toString());
const mimeType = mime.getType(path.extname(resolvedPath));
if (mimeType) headers.set("Content-Type", mimeType);
return NextResponse.json(file, { status: 200, headers });
}When I call the API, the image is just the generic missing file icon, even though the buffer seems to be entirely there and the status is 200:
Answered by Giant panda
Just figured it out. You can return an instance of the regular
That's the only line I had to change.
Response object like so:return new Response(file.buffer, { headers });That's the only line I had to change.
1 Reply
Giant pandaOP
Just figured it out. You can return an instance of the regular
That's the only line I had to change.
Response object like so:return new Response(file.buffer, { headers });That's the only line I had to change.
Answer