Search code examples
expresssveltekitsvelte-3

Deploying Sveltekit app proxying api to a backend on different port


I have developed a sveltekit app. During a development phase, I use a Vote configuration to proxy my api to a backend on same domain but different port. It works perfectly but when I compile for deployment the proxy stopped working. I saw that vite provides proxy only during development. How can I have a proxy also in production? Do I need an express project to host my compiled sveltekit app and proxy routes to the backend?


Solution

  • Ok I think I got it.

    As mentioned in the official sveltekit node adapter

    https://github.com/sveltejs/kit/tree/master/packages/adapter-node

    I need to create a custom server for example using expressjs. From there using the http proxy I'm able to forward all the routes /api to the backend on port 3001

    import { handler } from './build/handler.js';
    import express from 'express';
    import proxy from 'express-http-proxy';
    
    const app = express();
    const port = 3000;
    const backend = 3001;
    
    app.use('/api', proxy(`http://localhost:${backend}`));
    
    app.use(handler);
    
    app.listen(port, () => {
      console.log(`Wine Diagnostic Frontend listening on port ${port}`);
      console.log(`Reverse proxy forwarding to port ${backend}`);
    });
    

    As the guide says, the important thing to do after the sveltekit project is compiled, is to use the handler.js and not app.js in order to use a custom server.