I’m developing a PWA using Nuxt3, where my frontend runs on http://localhost:3000 and my backend (Django) runs on http://127.0.0.1:8000. I’m facing issues with service worker scope and API request proxying in a development environment.
Background:
My service worker is configured to cache and manage API requests.
API requests in development are directed to /api/*, which should proxy to localhost:8000 for the backend.
I use Vite’s proxy settings in nuxt.config.js to manage this in development (nuxt dev), which works fine.
// nuxt.config.js
defineNuxtConfig({
runtimeConfig: {
public: {
apiUrl: process.env.BASE_API_URL || "/api/",
},
},
vite: {
server: {
proxy: {
"/api": {
target: process.env.BACKEND_URL,
changeOrigin: true,
},
},
},
},
})
// index.vue
const runtimeConfig = useRuntimeConfig();
const { data, error, pending } = useFetch(`${runtimeConfig.public.apiUrl}events/`);
Problem:
According to the @vite-pwa/nuxt documentation, I need to run npm dev:preview:build
, in order to create and inject the PWA service worker into my app.
"dev:preview:build": "nuxt build && nuxt start",
By running this command, I switch to a production-like environment locally. The problem is that Vite’s proxy settings do not apply. Thus, my service worker cannot intercept these out-of-scope API requests since they are directed to a different port.
Solution Attempts:
- Standalone Proxy Server: Considered running a separate proxy server, but it would change the domain from localhost:3000 to localhost:3001, thus falling outside the service worker’s scope.
- Nuxt Server Middleware: Tried implementing server middleware in Nuxt to proxy requests, but faced issues ensuring it works similarly across nuxt dev and nuxt start.
Question:
How can I configure my Nuxt3 setup so that the service worker can intercept API requests to my Django backend on a different port in both development and a local production-like environment?
Ideally, I need a solution that works seamlessly for both nuxt dev and nuxt build && nuxt start without falling outside the service worker’s scope.
I don’t foresee the same issue in my production environment, as it’s configured to serve front- and backend from the same url. However, I just can’t understand how I can test this all locally. Perhaps its as easy as using a different command to nuxt build && nuxt start
?
Thank you for any help or pointers to resolve this issue!