Giter Site home page Giter Site logo

nuxt-proxy's Introduction

nuxt-proxy

Version NPM

Http-proxy middleware for Nuxt and h3.

Before using

Check out H3's built-in proxyRequest helper before using this module.

Installation

npm install nuxt-proxy

Usage

export default defineNuxtConfig({
  modules: ['nuxt-proxy'],
  // See options here https://github.com/chimurai/http-proxy-middleware#options
  proxy: {
    options: {
      target: 'https://jsonplaceholder.typicode.com',
      changeOrigin: true,
      pathRewrite: {
        '^/api/todos': '/todos',
        '^/api/users': '/users'
      },
      pathFilter: [
        '/api/todos',
        '/api/users'
      ]
    }
  },
  // OR
  // runtimeConfig: {
  //   proxy: {...}
  // }
})

// GET /api/todos -> https://jsonplaceholder.typicode.com/todos [304]
// GET /api/users -> https://jsonplaceholder.typicode.com/users [304]
<script setup>
// Base url is required
const { data } = useFetch('http://localhost:3000/api/todos')
</script>

You can pass an array of options for multiple targets.

Runtime config

NUXT_PROXY_OPTIONS_TARGET=https://reqres.in/api
export default defineNuxtConfig({
  modules: ['nuxt-proxy'],
  runtimeConfig: {
    proxy: {
      options: { target: 'https://jsonplaceholder.typicode.com', ...{ /* config */} }
    }
  }
})
// GET /api/users -> https://reqres.in/api/users [304]

License

MIT

nuxt-proxy's People

Contributors

menthol avatar wobsoriano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nuxt-proxy's Issues

Cannot start in Windows

I cannot start in Windows.

reproduction :
https://github.com/teamboot88/reproduction

When I remove proxy property from nuxt.config.js, it's working.

[worker reload] [worker init] Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'                                 04:43:50  

  at new NodeError (node:internal/errors:387:5)
  at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1017:11)
  at defaultResolve (node:internal/modules/esm/resolve:1097:3)
  at nextResolve (node:internal/modules/esm/loader:163:28)
  at ESMLoader.resolve (node:internal/modules/esm/loader:841:30)
  at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
  at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
  at link (node:internal/modules/esm/module_job:75:36)

Release 0.2.1 appears to no longer function

I just recently upgraded to 0.2.1 and it appears to no longer function. I suspect a packaging issue.

When running nuxi dev I get the following error.

 ERROR  Cannot start nuxt:  Cannot find module '/Users/wobsoriano/tmp/nuxt-proxy/src/module'

It appears as though this path is referenced in the dist/module.mjs file, the content of which is.

import jiti from 'jiti';
export default jiti(null, { interopDefault: true })('/Users/wobsoriano/tmp/nuxt-proxy/src/module');

Not working with "OPTIONS" method

When I try to make an "options" request, the server sends me a 204 "no content" response.
image

Screenshot from postman for a request to Nuxt (PORT: 3000):
image

Screenshot from postman for a request to Django Rest Framework (PORT: 8000):
image

The proxy is working for GET or POST requests.

Not starting after build

Environment


Reproduction

Build and start or preview

Error

/path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/path-rewriter.js:4
const isPlainObj = require("is-plain-obj");
                   ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/my/project/.output/server/node_modules/is-plain-obj/index.js from /path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/path-rewriter.js not supported.
Instead change the require of index.js in/path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/path-rewriter.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/path-rewriter.js:4:20)
    at Object.<anonymous> (/path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/http-proxy-middleware.js:8:22)
    at Object.<anonymous> (/path/to/my/project/.output/server/node_modules/http-proxy-middleware/dist/index.js:18:33)
    at async Promise.all (index 0) {
  code: 'ERR_REQUIRE_ESM'
}
 ELIFECYCLE  Command failed with exit code 1.

Module '"nuxt-proxy/middleware"' has no exported member 'createProxyMiddleware'

Hi! 👋

I'm getting a TypeScript error when importing { createProxyMiddleware } from 'nuxt-proxy/middleware':

$ npx nuxi@latest init nuxt-proxy-import
$ cd nuxt-proxy-import
$ npm install
$ npm install nuxt-proxy
$ mkdir -p server/middleware
$ echo "import { createProxyMiddleware } from 'nuxt-proxy/middleware'" > server/middleware/proxy.ts
$ tsc --noEmit server/middleware/proxy.ts 
node_modules/nuxt-proxy/middleware.d.ts:1:15 - error TS2307: Cannot find module './dist/runtime/middleware' or its corresponding type declarations.

1 export * from './dist/runtime/middleware'
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~

server/middleware/proxy.ts:1:10 - error TS2305: Module '"nuxt-proxy/middleware"' has no exported member 'createProxyMiddleware'.

1 import { createProxyMiddleware } from 'nuxt-proxy/middleware'
           ~~~~~~~~~~~~~~~~~~~~~


Found 2 errors in 2 files.

Errors  Files
     1  node_modules/nuxt-proxy/middleware.d.ts:1
     1  server/middleware/proxy.ts:1

Thanks for making this plugin!

Inject target from env at runtime instead of build time

As titled. Is it possible to inject the target value from environment variables at runtime instead of build time?

Using this option:

  proxy: {
    options: [
      {
        target: process.env.API_HOST,
        changeOrigin: true,
        pathRewrite: {
          '^/api/': '',
        },
        pathFilter: ['/api/'],
      },
    ],
  },

It's working fine when supplying the API_HOST value in the .env and bulid it, then run it. However, removing it from .env and supplying at runtime yields in this error:

Error: [HPM] Missing "target" option. Example: {target: "http://www.example.org"}

Edit: this issue especially occurs in production environment

http proxy error:Error: socket hang up

Nuxt 3.1.1
@nuxt-alt/proxy 2.2.0

Error
I've got many messages in console after start using this library:

http proxy error:Error: socket hang up                                                 23:55:41
    at connResetException (node:internal/errors:704:14)
    at TLSSocket.socketOnEnd (node:_http_client:505:23)
    at TLSSocket.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  timestamp: true,
  error: Error: socket hang up
      at connResetException (node:internal/errors:704:14)
      at TLSSocket.socketOnEnd (node:_http_client:505:23)
      at TLSSocket.emit (node:events:525:35)
      at endReadableNT (node:internal/streams/readable:1358:12)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ECONNRESET'
  }
}
http proxy error:Error: socket hang up                                                 23:55:41
    at connResetException (node:internal/errors:704:14)
    at TLSSocket.socketOnEnd (node:_http_client:505:23)
    at TLSSocket.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  timestamp: true,
  error: Error: socket hang up
      at connResetException (node:internal/errors:704:14)
      at TLSSocket.socketOnEnd (node:_http_client:505:23)
      at TLSSocket.emit (node:events:525:35)
      at endReadableNT (node:internal/streams/readable:1358:12)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ECONNRESET'
  }
}

Cannot load '/' path

// nuxt.config.ts
 export default defineNuxtConfig({
  modules: ["nuxt-proxy"],
  proxy: {
    options: {
      target: "http://localhost:1337",
      changeOrigin: true,
      secure: false,
      pathRewrite: {
        "^/api/": "/api/",
      },
      pathFilter: ["/api/"],
    },
  },
});
// xx.vue 
const { data: post, refresh } = await useAsyncData("nav", () =>
  $fetch("/api/meta")
);

http://localhost:3000/ load failed;

http://localhost:3000/api/meta is ok ;

Alt text
Alt text

[Feature]: Multiple Targets

Is it possible to have multiple proxy targets using this module ?

In the nuxt 2 proxy module, the proxy option takes either an array of configs or an object.
ie:

export default defineNuxtConfig({
  proxy:[
    {
      target: 'http://api1.domain.com',
      pathFilter: [
        '/api/v1/**'
      ]
    },
    {
      target: 'http://api2.domain.com',
      pathFilter: [
        '/api/v2/**'
      ]
    }
  ]
})

Page request stuck at "pending"

After configuring the module as follows, it didn't work

export default defineNuxtConfig({
  modules: ['nuxt-proxy'],
  // See options here https://github.com/chimurai/http-proxy-middleware#options
  proxy: {
    target: 'http://localhost:8080',
    changeOrigin: true,
    pathRewrite: {
      '^/find/suchen/': ''
    },
    pathFilter: [
      '/find/suchen',
    ]
  },
}

There is no error log. Request is simply stuck at "pending"

Proxying everything, but expected /api

Hi. I'm using "nuxt-proxy" in defineNuxtConfig this way:
modules: [ "nuxt-proxy", ], proxy: { ws: true, logger: console, options: { pathFilter: "/api", target: "http://172.16.5.106:2020", changeOrigin: true, pathRewrite: { "/api": "", }, }, }
I expect this proxy to be:
[HPM] Proxy created: /api -> http://

But instead I've got this:
[HPM] Proxy created: / -> http://

I've tried runtimeConfig, but it's the same.

Dependencies:
nuxt 3.6.1
[email protected]

Allow custom matching in pathFilter option

Greetings,

I am intending to utilize this module for conditional proxy purposes. In order to branch according to the expected accept: header in the request, I wrote a function in the pathFilter as follows:

pathFilter: (path, req) => accepts(req).types(['json', 'html']) === 'json'

Using custom matching in the pathFilter is well-explained in the http-proxy-middleware documentation:
https://github.com/chimurai/http-proxy-middleware#pathfilter-string-string-glob-glob-function

However, due to an attempt to serialize the options as JSON in the source code at https://github.com/wobsoriano/nuxt-proxy/blob/main/src/module.ts#L35, my approach does not function as anticipated. Is there a better way to preserve the original options during the process of generating virtual source code?

Is this a solution for nuxt3 cross domain proxy please?

//nuxt.config.ts
modules: [
    '@vueuse/nuxt',
    '@pinia/nuxt',
    '@nuxtjs/color-mode',
    'nuxt-proxy',
  ],

proxy: {
    options: {
      target: 'https://localhost:8100',
      changeOrigin: true,
      pathRewrite: {
        '^/api/': '/',
      },
      pathFilter: [
        '/api/',
      ],
    },
  },
//~/api/auth.ts
getInfo() {
      return useFetch('/api/auth/auth-member/info', {
        method: 'GET',
        headers: {
          Authorization: useCookie('token').value,
        },

      })
    },

image

Not possible to be used with useAsyncData?

I use the exact same config as in the README, and attempted to fetch the API from useAsyncData using $fetch like so:

const { data } = useAsyncData('todos', () => $fetch(`${baseUrl}/api/todos`), { transform: ({ data }) => data })

But the page is just stuck at pending. Using it with useFetch seems to be working fine, though. It's particularly weird since the Nuxt's doc mentioned that useFetch is just a wrapper around useAsyncData and $fetch.

It also seems to be working fine when $fetch is used in CSR (i.e., onMounted).

Error on deploy

I am using Google Cloud run when deploying my site. The plugin works 100 in development but getting the following build error.

TypeError: debug_1.Debug.extend is not a function
at Object. (/usr/src/app/.output/server/node_modules/http-proxy-middleware/dist/plugins/default/debug-proxy-errors-plugin.js:5:29)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object. (/usr/src/app/.output/server/node_modules/http-proxy-middleware/dist/plugins/default/index.js:17:14)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)

In my docker file I expose port 8080, not sure if the could be the reason?
ERROR: (gcloud.run.services.update) Cloud Run error: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.

Working from server/api

I want to use $fetch on server side and query through proxy.

How not to hardcode localhost:3000 ?

Can i bypass internal connection and fetch on route resolved connection?

not working on production generate mode nuxt3

My code is like
// proxy: {
// options: {
// target: 'http://example.com:8000',
// changeOrigin: true,
// pathRewrite: {
// '/auth': '/auth',
// '/site-test': '/site-test',
// '/site-prod': '/site-prod',
// },
// pathFilter: [
// '/auth',
// '/site-test',
// '/site-prod'
// ]
// }
// },
it works fine in devmode but when i write npm run generate and run .\output\public it returns 404

Not working with Nuxt 3.1.1: Every url goes through the proxy `/ -> PROXY`

I have Nuxt 3.1.1 with nuxt-proxy 0.3.12

part of nuxt config:

  proxy: {
    options: [
      {
        target: "http://" + PROXY,
        changeOrigin: true,
        pathFilter: ["/api/"],
        pathRewrite: {
          "^/api/": "",
        },
      },
      {
        target: "http://" + PROXY,
        changeOrigin: true,
        ws: true,
        pathFilter: ["/socket.io"],
      },
    ],
  },

Log output:

[HPM] Proxy created: /  -> http://127.0.0.1:3030                                                                                                      
[HPM] Proxy rewrite rule created: "^/api" ~> ""                                                                                                        
[HPM] Proxy created: /  -> http://127.0.0.1:3030  

Every url goes through the proxy

500 error for ssr request,

hi there,
i'm using nuxt-proxy and it works well on client-side, my mean is if you call a request on browser(for example submiting a form or clicking on a RouterLink) but it doesn't work if my request runs on server-side(for example when i refresh my page and i have a await useFetch() request on top of script setup) in this case it gives me error with 500 status code.

nuxt.config.ts

export default defineNuxtConfig({
  modules: ["nuxt-proxy"],
  proxy: {
    options: {
      target: "https://example.com",
      changeOrigin: true,
      pathRewrite: {
        "^/webapi": "/", 
      },
      pathFilter: ["/webapi/"],
    },
  },
....
})

i receive this error when i refresh my page and request runs on nuxt server-side
http-proxy

but this request works fine on client-side
How can I fix it? I want this to work on client-side and server-side

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.