feat: add API route for serving images with path validation

This commit is contained in:
Nils-Johan Gynther
2026-04-16 19:10:06 +02:00
parent 3f4fe890df
commit 1b9df4d20d
2 changed files with 39 additions and 0 deletions
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from 'next/server';
import * as fs from 'fs';
import * as path from 'path';
const IMAGE_DIR = process.env.IMAGE_DIR || '/app/public/images';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ filename: string }> },
) {
const { filename } = await params;
// Förhindra path traversal
if (!filename || filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
return new NextResponse('Not found', { status: 404 });
}
const filePath = path.join(IMAGE_DIR, filename);
if (!fs.existsSync(filePath)) {
return new NextResponse('Not found', { status: 404 });
}
const file = fs.readFileSync(filePath);
return new NextResponse(file, {
headers: {
'Content-Type': 'image/jpeg',
'Cache-Control': 'public, max-age=31536000, immutable',
},
});
}