question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeScript regression in 2.0.3

See original GitHub issue

Checks

Describe the bug (be clear and concise)

import { createProxyMiddleware, Options } from 'http-proxy-middleware';
import { AppSettings } from '../../../functions/AppSettings';

// Great way to avoid using CORS and to transparently add Access Token to API requests
// Proxy requests from /api/demo/... to http://localhost:5000/...
const apiProxyOptions: Options = {
    target: AppSettings.current.backendHost,
    changeOrigin: true,
    // Set ws to true if proxying WebSocket
    // Recommendation: create a dedicated API gateway for WebSocket, don't mix!
    // If troublesome, just hit the WebSocket endpoint directly (CORS)
    ws: false,
    xfwd: true,
    pathRewrite: {
        '^/api/demo': '/'
    },
    logLevel: 'warn'
};

const apiProxy = createProxyMiddleware(apiProxyOptions);

const apiGateway = async (req, res) => {
    apiProxy(req, res, (result: unknown) => {
        if (result instanceof Error) {
            throw result;
        }

        throw new Error(`Failed to proxy request: '${req.url}'`);
    });
}

export default apiGateway;

export const config = {
    api: {
        externalResolver: true,
    },
}

This is the entire code.

In version 2.0.2, that code can be does not emit compile error in TypeScript.

But when upgrading to version 2.0.3, an error appeared:

[2:24:03 PM] Starting compilation in watch mode...

pages/api/demo/[...apiGateway].ts:23:5 - error TS2349: This expression is not callable.
  Type 'RequestHandler' has no call signatures.

23     apiProxy(req, res, (result: unknown) => {
       ~~~~~~~~

[2:24:05 PM] Found 1 error. Watching for file changes.

Step-by-step reproduction instructions

Place the above code in a TypeScript project.

If require a reproduction repository, run these commands:

git clone https://github.com/accelist/nextjs-starter
npm install http-proxy-middleware@2.0.3 -E
npm update
npm run typescript

Expected behavior (be clear and concise)

No TypeScript type error in version 2…0.3

How is http-proxy-middleware used in your project?

PS D:\VS\accelist-nextjs-starter> npm ls http-proxy-middleware
accelist-nextjs-starter@1.0.0 D:\VS\accelist-nextjs-starter
`-- http-proxy-middleware@2.0.2

What http-proxy-middleware configuration are you using?

const apiProxyOptions: Options = {
    target: AppSettings.current.backendHost,
    changeOrigin: true,
    // Set ws to true if proxying WebSocket
    // Recommendation: create a dedicated API gateway for WebSocket, don't mix!
    // If troublesome, just hit the WebSocket endpoint directly (CORS)
    ws: false,
    xfwd: true,
    pathRewrite: {
        '^/api/demo': '/'
    },
    logLevel: 'warn'
};

What OS/version and node/version are you seeing the problem?

System:
    OS: Windows 10 10.0.19044
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 22.21 GB / 31.85 GB
  Binaries:
    Node: 16.13.2 - C:\Program Files\nodejs\node.EXE
    npm: 8.1.2 - C:\Program Files\nodejs\npm.CMD
  Managers:
    pip3: 21.1.3 - ~\AppData\Local\Programs\Python\Python39\Scripts\pip3.EXE
  Utilities:
    Git: 2.34.0.
  Virtualization:
    Docker: 20.10.12 - C:\Program Files\Docker\Docker\resources\bin\docker.EXE
  SDKs:
    Windows SDK:
      AllowDevelopmentWithoutDevLicense: Enabled
      AllowAllTrustedApps: Enabled
  IDEs:
    Android Studio: Version  4.2.0.0 AI-202.7660.26.42.7351085
    VSCode: 1.64.2 - C:\Users\Ryan\AppData\Local\Programs\Microsoft VS Code\bin\code.CMD
    Visual Studio: 17.1.32210.238 (Visual Studio Community 2022)
  Languages:
    Bash: 5.0.17 - C:\Windows\system32\bash.EXE
    Java: 11.0.8
    Python: 3.9.6
  Browsers:
    Edge: Spartan (44.19041.1266.0), Chromium (98.0.1108.55)
    Internet Explorer: 11.0.19041.1566

Additional context (optional)

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
francescovenicacommented, Sep 7, 2022

http-proxy-middleware v3 added support for Next.js

It’s still in beta. You can give it a try and install it with npm install http-proxy-middleware@beta

Happy to hear your feedback.

https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md#nextjs

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { createProxyMiddleware } from 'http-proxy-middleware';

const proxyMiddleware = createProxyMiddleware({
  target: 'http://jsonplaceholder.typicode.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api/users': '/users',
  },
});

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  proxyMiddleware(req, res, (result: unknown) => {
    if (result instanceof Error) {
      throw result;
    }
  });
}

export const config = {
  api: {
    externalResolver: true,
  },
};

// curl http://localhost:3000/api/users

Using apollo client I had to change the config in this way:

export const config = {
  api: {
    bodyParser: false,
    externalResolver: true,
  },
};

otherwise the request get stuck in pending.

2reactions
chimuraicommented, Apr 23, 2022

http-proxy-middleware v3 added support for Next.js

It’s still in beta. You can give it a try and install it with npm install http-proxy-middleware@beta

Happy to hear your feedback.

https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md#nextjs

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { createProxyMiddleware } from 'http-proxy-middleware';

const proxyMiddleware = createProxyMiddleware({
  target: 'http://jsonplaceholder.typicode.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api/users': '/users',
  },
});

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  proxyMiddleware(req, res, (result: unknown) => {
    if (result instanceof Error) {
      throw result;
    }
  });
}

export const config = {
  api: {
    externalResolver: true,
  },
};

// curl http://localhost:3000/api/users
Read more comments on GitHub >

github_iconTop Results From Across the Web

@types/regression - npm
TypeScript definitions for regression. Latest version: 2.0.2, last published: a year ago. Start using @types/regression in your project by ...
Read more >
@types/regression | Yarn - Package Manager
Fast, reliable, and secure dependency management.
Read more >
What is the TypeScript 2.0 / ES2015 way to import assert from ...
For Node 10 and above, it's better to use strict assert which can be imported as named import and renamed for convenience as...
Read more >
percy-agent dashboard
#598 build(deps-dev): bump typescript from 4.0.5 to 4.1.3 Deleted User ... dependabot-preview[bot] build(deps-dev): bump tslib from 2.0.0 to 2.0.3 (#582).
Read more >
Setup | TensorFlow.js
When using TypeScript you may need to set skipLibCheck: true in your tsconfig.json file if your project makes use of strict null checking...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found