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
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;
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;
}
}
Now hot module reloading (HMR) works over nginx!
Top comments (2)
Thank you. This helped me a lot as well.
This might have saved me a good amount of work, thank you so much