Since @nuxt/proxy
is not yet ready for Nuxt 3, I stole the code and used my own module temporarily. Unfortunately, the proxy only seems to work when in development mode. As soon as I build and run the server, the proxy is disabled. Broken down to the bare minimum, the module is:
import { addServerMiddleware, defineNuxtModule } from "@nuxt/kit-edge";
import { createProxyMiddleware } from "http-proxy-middleware";
export default defineNuxtModule({
setup(options, nuxt) {
addServerMiddleware({
handler: createProxyMiddleware(
"/uploads",
{ target: "http://localhost:1337/" }
),
});
},
});
The relevant parts of my nuxt.config.js
are:
export default defineNuxtConfig({
buildModules: ["~/modules/proxy"],
[...]
});
I also tried moving it to modules
instead:
export default defineNuxtConfig({
modules: ["~/modules/proxy"],
[...]
});
During build, the module is clearly run, as createProxyMiddleware
logs the proxy to the console:
> nuxi build
Nuxt CLI v3.0.0-27369360.33ebb01 14:00:06
ℹ [HPM] Proxy created: /uploads -> http://localhost:1337/ 14:00:08
ℹ Vite warmed up in 3517ms 14:00:13
ℹ Client built in 8150ms 14:00:17
ℹ Building server... 14:00:17
✔ Server built in 1899ms 14:00:19
ℹ Nitro preset is server 14:00:19
ℹ Cleaning up .output 14:00:19
start Generating public... 14:00:19
✔ Generated public .output/public 14:00:19
start Building server... 14:00:19
start Writing server bundle... 14:00:23
✔ Server built 14:00:23
├─ .output/server/index.mjs (69.6 kB) (23.7 kB gzip)
├─ .output/server/chunks/nitro/static.mjs (11.1 kB) (2.92 kB gzip)
├─ .output/server/chunks/index.mjs (392 kB) (90.3 kB gzip)
├─ .output/server/chunks/app/vue3.mjs (284 B) (200 B gzip)
├─ .output/server/chunks/app/server.mjs (240 kB) (55.2 kB gzip)
├─ .output/server/chunks/app/render.mjs (23 kB) (6.41 kB gzip)
└─ .output/server/chunks/app/client.manifest.mjs (11.4 kB) (1.43 kB gzip)
Σ Total size: 1.68 MB (460 kB gzip)
ℹ You can preview this build using nuxi preview
But when I run the server, the proxy is not active. Lacking documentation, I presumed addServerMiddleware
would work the same way addPLugin
from @nuxt/kit
works. Any ideas what I'm doing wrong?
Following http-proxy-middleware package recipe for Next.js I came up with solution:
Define server middleware /server/middleware/proxy.ts
import { createProxyMiddleware } from 'http-proxy-middleware';
const proxyMiddleware = createProxyMiddleware(
"/uploads",
{ target: "http://localhost:1337/" }
);
export default (req, res) => {
proxyMiddleware(req, res, (result: unknown) => {
if (result instanceof Error) {
throw result;
}
});
}
More about Nuxt3 Server Routes
UPDATE
Nuxt3 compatible proxy module
https://github.com/wobsoriano/nuxt-proxy