sveltekitstatic-contentsveltekit-adapter-node

SvelteKit handle a static image folder


I build an anonymous board with SvelteKit, it can handle the user uploaded image, and save it to path like <project_folder>/static/images/abc.jpg, and we can access it with a URL http://localhost:5173/images/abc.jpg. It works well when in dev mode.

But when I build with adapter-node, the adapter will generate a <project_folder>/build folder like this:

build
├ client
│ ├ _app
│ │ └ (other file)
│ ├ favicon.svg // the files in `<project_folder>/static` folder

When user upload a file at runtime, like def.png, the logic in my code will create a file in <project_folder>/static/images folder, so when I access <site_url>/images/def.png in build production, It will try to find <project_folder>/build/images/def.png, Obviously will get a 404 error, like this:

SvelteKitError: Not found: /images/6cc7f9f5268c4a2a9c85883e25310d39.jpg
    at resolve2 (file:///<project_folder>/build/server/index.js:4291:18)
    at resolve (file:///<project_folder>/build/server/index.js:4124:34)
    at resolve (file:///<project_folder>/build/server/chunks/hooks.server-QmY9mL2g.js:30:16)
    at db (file:///<project_folder>/build/server/chunks/hooks.server-QmY9mL2g.js:49:26)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async respond (file:///<project_folder>/build/server/index.js:4122:22)
    at async Array.ssr (file:///<project_folder>/build/handler.js:1284:3) {
  status: 404,
  text: 'Not Found'
}

What should I do to solve the difference of devolopment and production? this may be opinion below:

  1. In the save upload file code logic, differences the dev and prod save path
  2. create a endpoint for images access, differences the dev and prod visit path

Or other simple solution for it?


Solution

  • TL;DR:

    move out the upload image folder from static folder

    because static folder will be complied by copying its contain files to build/client, and do somthing others

    and Svelte tutorial in this page, said about static folder

    Any static assets that should be served as-is

    So I think should not place dynamic, user generate content here

    Project Structure

    before

    ├ src
    ├ static
    │ ├ images
    │ │ └ (upload images here)
    │ ├ favicon.svg
    │ └ (other static files)
    ├ (other files)
    

    after

    ├ src
    ├ static
    │ ├ favicon.svg
    │ └ (other static files)
    ├ uploadImages // new place, not only here, but also other place you can access
    │ └ (upload images here)
    ├ (other files)
    

    in this way, we can achieve many things:

    1. there is no difference between dev and other mode
    2. we can make a configuation in .env file to select other folder
    3. it can also handle by web server software, like nginx, if I put it in like /opt/anonymous_board/upload_images, there is no need to serve the images by Node.js