Nuxt Proxy Middleware

raw JSON →
0.4.1 verified Thu Apr 23 auth: no javascript

nuxt-proxy is a Nuxt 3 module that integrates `http-proxy-middleware` and `h3` to provide HTTP proxying capabilities directly within a Nuxt application. It enables developers to configure declarative proxy rules in `nuxt.config.ts`, facilitating the routing of specific client-side API requests to backend servers. This is commonly used to circumvent CORS restrictions or to unify API endpoints under a single origin. The current stable version is 0.4.1. Releases typically focus on bug fixes, dependency updates (e.g., `h3`, `@nuxt/kit`), and minor feature enhancements such as runtime configuration overrides. Its key differentiator is a streamlined, module-based setup within the Nuxt ecosystem, leveraging Nuxt's Nitro server for efficient middleware handling, offering a more integrated solution than manually setting up a proxy.

error GET http://localhost:3000/api/todos 404 (Not Found)
cause The proxy rule's `pathFilter` is not matching the incoming request path, or `pathRewrite` is incorrectly configured, leading to the request not being intercepted or forwarded to the wrong backend path, resulting in a 404 from the Nuxt server or the backend.
fix
Verify that your pathFilter regex or array includes the requested path (/api/todos). Ensure pathRewrite correctly transforms the path to what the target API expects (e.g., from /api/todos to /todos). Double-check the target URL for accuracy and connectivity.
error Access to XMLHttpRequest at 'http://backend.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cause Despite using a proxy to circumvent CORS, the backend server might still be enforcing CORS policies. This can happen if `changeOrigin: true` is not set in the proxy options, or if the backend itself doesn't send the appropriate CORS headers for the proxied request.
fix
Add changeOrigin: true to your proxy.options in nuxt.config.ts. If the issue persists, the backend server itself may need configuration to allow requests from the origin the proxy presents, or to include Access-Control-Allow-Origin headers for the proxied requests.
error Error: Cannot find module 'http-proxy-middleware' imported from <some-path>/nuxt-proxy/dist/module.mjs
cause This error typically occurs in specific environments (e.g., pnpm with certain strict settings) where `http-proxy-middleware` might not be correctly resolved as an ESM module, despite fixes in recent `nuxt-proxy` versions.
fix
Ensure you are using nuxt-proxy@0.4.1 or newer. If using pnpm, try adding a .pnpmfile.cjs or package.json pnpm.patchedDependencies entry to explicitly patch http-proxy-middleware for ESM compatibility, as indicated in nuxt-proxy's changelog, if the issue persists.
error Proxy configuration not applied from environment variable NUXT_PROXY_OPTIONS_TARGET
cause The environment variable for proxy configuration is either misspelled, not correctly prefixed for Nuxt's runtime config, or is being overridden by a more specific configuration.
fix
Ensure the environment variable is correctly named, typically NUXT_PROXY_OPTIONS_TARGET for the root proxy options target. Verify that runtimeConfig.proxy is set up in nuxt.config.ts to consume these environment variables, and there are no other configurations with higher precedence overriding it.
gotcha The `nuxt-proxy` README explicitly advises checking h3's built-in `proxyRequest` helper before using this module. For simple proxy needs, `h3`'s native solution might be more lightweight and performant.
fix Evaluate if `h3.proxyRequest` meets your requirements. If so, consider using it directly in a Nuxt server route (`server/api/**/*.ts`) instead of `nuxt-proxy`.
gotcha Past ESM compatibility issues with `http-proxy-middleware` (via pnpm patch) were noted in v0.4.1. While fixed, this indicates potential for environment-specific issues, especially with package managers like pnpm or strict ESM setups.
fix Ensure you are on `nuxt-proxy@0.4.1` or newer. If issues persist, verify your `pnpm` workspace configuration and check `http-proxy-middleware` for specific ESM caveats.
gotcha Understanding the precedence of proxy configuration is crucial. Options can be set directly in `defineNuxtConfig.proxy`, in `runtimeConfig.proxy`, and via environment variables. Incorrect placement or naming can lead to settings not being applied.
fix Consult the documentation on runtime configuration. Typically, environment variables take precedence over `runtimeConfig`, which in turn overrides direct `proxy` configuration in `defineNuxtConfig`.
gotcha Misconfiguration of `pathRewrite` and `pathFilter` options can lead to requests not being proxied correctly or being sent to unintended backend paths. `pathFilter` defines which paths activate the proxy, while `pathRewrite` modifies the path before forwarding.
fix Carefully review the `http-proxy-middleware` documentation for `pathRewrite` and `pathFilter` syntax and behavior. Test proxy routes thoroughly to ensure they resolve to the expected backend endpoints.
npm install nuxt-proxy
yarn add nuxt-proxy
pnpm add nuxt-proxy

Demonstrates how to enable `nuxt-proxy` as a module, configure basic proxy rules in `nuxt.config.ts` including `target`, `pathRewrite`, and `pathFilter`, and show how client-side `useFetch` interacts with the proxied endpoints. It also includes an example of runtime configuration.

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  modules: [
    'nuxt-proxy'
  ],
  proxy: {
    options: {
      target: process.env.NUXT_PROXY_TARGET ?? 'https://jsonplaceholder.typicode.com',
      changeOrigin: true,
      pathRewrite: {
        '^/api/todos': '/todos',
        '^/api/users': '/users'
      },
      pathFilter: [
        '/api/todos',
        '/api/users'
      ]
    }
  },
  // Example of using runtimeConfig for proxy options
  runtimeConfig: {
    proxy: {
      options: {
        target: process.env.NUXT_RUNTIME_PROXY_TARGET ?? 'https://jsonplaceholder.typicode.com'
      }
    }
  }
});

// In a Vue component or server route (e.g., pages/index.vue)
// <script setup>
// const { data: todos } = await useFetch('/api/todos');
// console.log('Fetched Todos:', todos.value);
// const { data: users } = await useFetch('/api/users');
// console.log('Fetched Users:', users.value);
// </script>