Http-proxy middleware for Nuxt 3.

Related tags

Vue.js vue proxy nuxt
Overview

nuxt-proxy

Version

Http-proxy middleware for Nuxt 3.

Installation

npm install nuxt-proxy

Usage

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

// GET /api/todos -> https://jsonplaceholder.typicode.com/todos [304]
// GET /api/users -> https://jsonplaceholder.typicode.com/users [304]
<script setup>
// Need the base url or it will load forever
const { data } = useFetch('http://localhost:3000/api/todos')
</script>

Usage with h3

import { createApp } from 'h3'
import { createProxyMiddleware } from 'nuxt-proxy/middleware'

const app = createApp()

app.use(createProxyMiddleware({}))

License

MIT

Comments
  • feat: allow overrides config by env variable

    feat: allow overrides config by env variable

    Hi

    You have merged my contribution, but you have removed its main benefit.

    The need addressed is to be able to override the proxy configuration at runtime. This way it is possible to compile with default options and then run it with options adapted to the execution environment.

    I understood what you tried to do by allowing the use of the "runtimeConfig" configuration in "nuxt.config.ts". So here is a new contribution that takes up what I understood from your idea and my initial need.

    Now its possible to use :

    NUXT_PROXY_OPTIONS=[{}, {"target": "http://proxy.target.for/second/proxy"}]
    # NUXT_PROXY_OPTIONS_TARGET=http://target.for/single-proxy
    
    opened by menthol 3
  • Not possible to be used with useAsyncData?

    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).

    opened by marssantoso 3
  • Page request stuck at

    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"

    opened by odai-alali 3
  • Cannot start nuxt:  Cannot read properties of undefined (reading 'push')

    Cannot start nuxt: Cannot read properties of undefined (reading 'push')

    I am getting Cannot start nuxt: Cannot read properties of undefined (reading 'push') error with:

    nuxt 3.0.0 nuxt-proxy 0.3.4

    Any ideas what is going wrong?

    opened by PavlosMac 2
  • Inject target from env at runtime instead of build time

    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

    opened by marssantoso 2
  • Release 0.2.1 appears to no longer function

    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');
    
    opened by andrew-teirney 2
  • [Feature]: Multiple Targets

    [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/**'
          ]
        }
      ]
    })
    
    opened by Blemming 2
  • Cannot load '/' path

    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

    opened by xiaoxiaoqian1217 1
  • Error on deploy

    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.

    opened by PMLS3 1
  • Not starting after build

    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.
    
    opened by KhaledAlMana 0
  • Not working with

    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.

    opened by DanieleMilillo13 0
  • Is this a solution for nuxt3 cross domain proxy please?

    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

    opened by balck-paint 1
Releases(v0.3.7)
Owner
Robert Soriano
[object Object]
Robert Soriano
⚡️ Minimal GraphQL Client + Code Generation for Nuxt

nuxt-graphql-client ⚡️ Minimal GraphQL Client + Code Generation for Nuxt ⚡️ Minimal GraphQL Client + Code Generation for Nuxt Features Zero Configurat

Dizzy 245 Dec 27, 2022
Nuxt.js module to use Unleash toggle feature services

nuxt-unleash Nuxt.js module to use Unleash toggle feature services ?? Release Notes Features Use $unleash to access and handle your Unleash feature fl

Juanjo Conejero 15 Dec 3, 2022
Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 📋

nuxt-social-tags Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 ✨ Release Notes ?? Read the documentation Features Nuxt3 ready Composables

Conner 19 Dec 17, 2022
Easily connect your Nuxt 3 application with LogSnag 📰

Nuxt LogSnag ?? LogSnag integration for Nuxt 3 ✨ Release Notes Features Nuxt 3 ready Easy integration Handy composables TypeScript support Setup Insta

Conner 13 Apr 28, 2022
Nuxt 3 starter with Algolia, Storyblok, and Indexer

Nuxt 3 with Storyblok CMS and Algolia Search (incl. automatic indexing) This is a demo repository for an article in Dev.to. We recommend to look at th

Jakub Andrzejewski 5 May 24, 2022
End-to-end typesafe APIs with tRPC.io in Nuxt applications.

tRPC-Nuxt End-to-end typesafe APIs with tRPC.io in Nuxt applications. The client above is not importing any code from the server, only its type declar

Robert Soriano 231 Dec 30, 2022
A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free • Open Source • Notification View Demo · Report Bug · Requ

zernonia 208 Dec 27, 2022
🔎 Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt ✨ Release Notes ?? Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Nuxt Community 128 Jan 7, 2023
Nuxt 3 module for Kirby's Query Language API

nuxt-kql Kirby KQL module for Nuxt 3. This module provides a useKql composable, which under the hood uses useFetch. Thus, KQL query fetching in your N

Johann Schopplich 25 Dec 15, 2022
This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configured and ready to use in real world projects!

Nuxt 3 Starter This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configure

Ali Soueidan 26 Dec 27, 2022
Batteries-included, zero-config Ionic integration for Nuxt

Nuxt Ionic Ionic integration for Nuxt ✨ Changelog ?? Read the documentation ▶️ Online playground Features ⚠️ nuxt-ionic is currently a work in progres

Daniel Roe 211 Dec 28, 2022
Nuxt 3 module for Web3.js

nuxt-web3.js Nuxt 3 module for Web3.js. Installation npm install nuxt-web3.js Usage export default defineNuxtConfig({ modules: ['nuxt-web3.js'], })

Robert Soriano 8 Dec 16, 2022
OpenID-Connect(OIDC) integration module for nuxt 3.0.

Nuxt OpenID-Connect OpenID-Connect(OIDC) integration module for nuxt 3.0. Features An Nuxt 3 module. OIDC integration ( implemetation base openid-clie

Aborn Jiang 10 Dec 24, 2022
🔎 Meilisearch module for Nuxt 3

nuxt-meilisearch Meilisearch module for Nuxt Features Nuxt 3 Easy integration with MeilisearchJS lib Support for Vue Algolia Vue 3 InstantSearch compo

Alex Duval 50 Dec 26, 2022
A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free • Open Source • Notification View Demo · Report Bug · Requ

StatusBase 194 Jul 5, 2022
Nuxt eureka client

Nuxt eureka client

Kirill 5 May 30, 2022
✉️ Nuxt module for first class integration with popular newsletter providers

nuxt-newsletter Newsletter module for Nuxt 3 ✨ Release Notes ?? Read the documentation Features Nuxt 3 ready Easy integration with Mailchimp, Revue, B

Jakub Andrzejewski 39 Jan 5, 2023
🔎 Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt ✨ Release Notes ?? Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Nuxt Community 91 Jul 28, 2022
⚡️ Integrate Nuxt with Twind, The smallest, fastest, most feature complete tailwind-in-js solution in existence!

Nuxt Twind Module Integrate Nuxt with Twind, The smallest, fastest, most feature complete tailwind-in-js solution in existence! Warning ?? This module

pooya parsa 38 Oct 18, 2022