I have a preact frontend with a FastAPI backend. Everything works fine on localhost.
But I had problems reaching my server, from another ip-address, which i solved by changing the fetches from http://localhost:8000 to the ip address of the server machine. E.g. http://192.168.0.99:8000.
I am using the server on a raspberry pi which can change network, which is why i cannot use a static ip-address in the proxy. That’s how i came up with the following solution:
vite.config.js
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';
import os from 'os';
function getLocalIpAddress() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return "http://" + iface.address + ":8000";
}
}
}
return 'http://127.0.0.1:8000';
}
function getLocalIpAddressWs() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return "ws://" + iface.address + ":8000";
}
}
}
return 'ws://127.0.0.1:8000';
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [preact()],
server: {
port: 3000,
host: '0.0.0.0',
proxy: {
'/api': {
target: getLocalIpAddress(), // Replace with your backend server URL
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, ''),
},
'/socket': {
target: getLocalIpAddressWs(), // Replace with your backend server URL
changeOrigin: true,
rewrite: (path) => path.replace(/^/socket/, ''),
},
},
},
});
Is this bad practice? Is there a better solution?