Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svelte kit serve files in a directory as static files

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);
};
like image 629
seyed Avatar asked Sep 05 '25 21:09

seyed


1 Answers

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"
like image 197
Jonas Avatar answered Sep 11 '25 01:09

Jonas