Search code examples
svelteserver-side-renderingsveltekit

How to Enable CORS on a Sveltekit Standalone Endpoint?


I'm building an embed that needs access to a sveltkit endpoint from any origin.

If I was using express I would simply use the cors middleware.

I'm curious if there is a way to enable CORS on sveltkit endpoints so I don't need to spin up another service.

Some things I've tried so far:

  • Returning 'Access-Control-Allow-Origin': '*' from the get handle in the endpoint

  • Overriding the OPTIONS http method (never seems to get called)

  • I saw this reddit post but it seems outdated.


Solution

  • I figured it out!

    The answer will be different depending on the sveltkit adapter you are using. In my case I'm using the node adapter and can actually serve the svelte app from express and enable the cors middleware there:

    // this is file exported by the node adapter plugin
    import { handler } from './build/handler.js'; 
    import express from 'express';
    import cors from 'cors';
    
    const app = express();
    app.use(cors());
    
    // add a route that lives separately from the SvelteKit app 
    app.get('/healthcheck', (req, res) => { res.end('ok'); });
    
    // let SvelteKit handle everything else, including serving prerendered pages and static assets app.use(handler);
    
    app.listen(3000, () => { console.log('listening on port 3000'); });
    

    This is a modification of the "custom server" example in the documentation of the node adapter: https://kit.svelte.dev/docs/adapter-node#custom-server