I need to serve some files in a directory as static files in the Svelte kit. these files are created in runtime (e.g. user uploaded files). Is there any Svelte kit built-in way to serve these files? or I should use external packages like serve-static?
these files do not exist in compile time and the src/lib/assets
or static/
directory is unsuitable.
// src/routes/media/[...path]/+server.js
export const GET = async ({ params, request }) => {
const { path } = params;
if (isFileForbiden(path)) {
throw error(404);
}
// serve static files from '__media_root__/{path}
return serve(path);
};
you have to read the file and return the buffer with Response
.
src/routes/media/[...path]/+server.js
import path from 'node:path'
import fs from 'node:fs/promises'
import { error } from '@sveltejs/kit'
import { MEDIA_ROOT } from '$env/static/private'
import { isFileForbiden } from './isFileForbiden'
export const GET = async ({ params }) => {
const pathName = path.resolve(MEDIA_ROOT , params.path)
if (isFileForbiden(pathName)) throw error(403) // use 403 (forbiden) here
try {
const file = await fs.readFile(pathName)
return new Response(file)
} catch {
throw error(404) // use 404 (not found) here
}
}
e.g .env
MEDIA_ROOT="./media"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With