Display a PDF file in API Response
May 22, 2024
Setting Content-Disposition to inline we can display PDF files in API responses instead of downloading.
import { readFile } from 'fs/promises'
import { join } from 'path'
export async function GET(request: Request, { params }: { params: { fileName: string } }) {
try {
const filesPath = join(process.cwd(), params.fileName)
const fileBuffer = await readFile(filesPath)
return new Response(fileBuffer, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline'
})
} catch (error) {
return new Response(null, {
status: 500
})
}
}
Note: The API response display depends to the server configuration.