DEV Community

Yaroslav Polyakov
Yaroslav Polyakov

Posted on

4 1

Svelte-kit (vite) with HMR over NGINX (Solution)

I need to use svelte-kit over nginx reverse proxy (because of third-party cookies which requires HTTPS). If you will just make simple proxy on nginx, pages will load, but HMR will not work. You will get this error message on console:

[vite] failed to connect to websocket.
your current setup:
  (browser) example.com/ <--[HTTP]--> localhost:5173/ (server)
  (browser) example.com:/ <--[WebSocket (failing)]--> localhost:5173/ (server)
Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .
(anonymous) @ client.ts:48
(anonymous) @ client.ts:99
Enter fullscreen mode Exit fullscreen mode

Problem is you cannot easily proxy HTTP + websocket over one nginx server. But solution is simple:

add server.hmr.clientPort to vite.config.js:

import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    server: {
        hmr: {
            clientPort: 5111
        }
    }
};

export default config;
Enter fullscreen mode Exit fullscreen mode

This will make wss to work over different port, so you can use different configuration for HTTP and websockets in nginx:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/private/cert.pem;
    ssl_certificate_key /etc/ssl/private/key.pem;

    location / {
        proxy_pass http://127.0.0.1:5173;
        proxy_set_header Host $host;
    }
}

server {
    listen 5111 ssl;

    ssl_certificate     /etc/ssl/private/cert.pem;
    ssl_certificate_key /etc/ssl/private/key.pem;

    location / {
        proxy_pass http://127.0.0.1:5173;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;

    }
}
Enter fullscreen mode Exit fullscreen mode

Now hot module reloading (HMR) works over nginx!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
plufz profile image
Emil

Thank you. This helped me a lot as well.

Collapse
 
jgalonso profile image
jaime

This might have saved me a good amount of work, thank you so much

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs