Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Set specific headers for static files in SvelteKit

$
0
0

I need to serve some files from my SvelteKit project with permissive CORS headers.

Some options I've explored:

Placing the files in /static

If I place those files in /static I get restrictive CORS headers.

Is there a way to customize headers for static files? I would guess not, based on this conversation: https://github.com/sveltejs/kit/issues/2060.

Placing the files in /lib

I can place the files elsewhere in the directory structure, then access them using readFile from within a +server.ts endpoint.

However, if I place the files in /lib and build, they do not get copied into the build output at an easily accessible path.

I can figure out the correct path manually, but it's brittle and only works when I'm running the pre-built project (i.e. only if I do npm build; npm preview, and not if I do npm dev).

Placing the files elsewhere and configuring an alias

Using the same custom endpoint approach as above, in theory I could:

  • create a new directory for my files
  • add that directory as an alias in vite.config.ts:
{    ...,    resolve: {        alias: {            $public: '/public'        }    }}
  • reference the file using the alias:
readFile(`$public/{params.filename}`)

However, when building, Vite does not rewrite $public to the correct path in the build output. It would appear that this path rewriting only works in certain situations.

Bypassing the build process

Again using the custom endpoint approach, I could add a new step to my Docker build to copy the files to a path outside of the SvelteKit build output and then read them from disk at that path.

Unfortunately I then don't get the benefit of any of the packaging that SvelteKit/Vite does when building my assets (e.g. compression).


Viewing all articles
Browse latest Browse all 1541

Trending Articles