• Stars
    star
    229
  • Rank 174,666 (Top 4 %)
  • Language
    TypeScript
  • Created over 4 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP Proxy middleware available in API Middleware provided by Next.js.

Next.js HTTP Proxy Middleware

NPM License NPM Downloads All Contributors

HTTP Proxy middleware available in API Middleware provided by Next.js.

⭐️ Before using

Please try the solutions below before using this library. 😀

Try using Next.js Rewrites(recommended)

Try using Http-Proxy

  • next-http-proxy-middleware is implemented using http-proxy internally. Since the implementation is not complicated, it is recommended to try http-proxy directly.
    // pages/api/[...all].ts
    import httpProxy from "http-proxy";
    
    export const config = {
      api: {
        // Enable `externalResolver` option in Next.js
        externalResolver: true,
        bodyParser: false,
      },
    };
    
    export default (req, res) =>
      new Promise((resolve, reject) => {
        const proxy: httpProxy = httpProxy.createProxy();
        proxy.once("proxyRes", resolve).once("error", reject).web(req, res, {
          changeOrigin: true,
          target: process.env.NEXT_PUBLIC_API_PROXY_URL,
        });
      });

Installation

The easiest way to install next-http-proxy-middleware is with npm.

npm install next-http-proxy-middleware

Alternately, download the source.

git clone https://github.com/stegano/next-http-proxy-middleware.git

Features

This middleware is implemented using the http-proxy library. You can use the existing options provided by http-proxy. And you can rewrite the api path using pathRewrite, an additional option provided by this middleware.

pathRewrite option

  • Replaces URL information matching the pattern with another string.
    • Priority is determined in the order entered in the array.
    • If the request URL matches the pattern pathRewrite.patternStr replace the URL string with the value pathRewrite.replaceStr.

onProxyInit option

  • You can access the http-proxy instance using the onProxyInit option. See the example below.

    const handleProxyInit = (proxy: httpProxy) => {
      /**
       * Check the list of bindable events in the `http-proxy` specification.
       * @see https://www.npmjs.com/package/http-proxy#listening-for-proxy-events
       */
      proxy.on('proxyReq', (proxyReq, req, res) => {
        ...
      });
      proxy.on('proxyRes', (proxyRes, req, res) => {
        ...
      });
    };
    
    export default async (req: NextApiRequest, res: NextApiResponse) 
      => httpProxyMiddleware(req, res, {
        ...
        target: 'http://example.com',
        onProxyInit: handleProxyInit,
      }
    );

Example

  • Refer to the following for how to use Next.js API Middleware

    // pages/api/[...all].ts
    export const config = {
      api: {
        // Enable `externalResolver` option in Next.js
        externalResolver: true,
      },
    }
    
    export default (req: NextApiRequest, res: NextApiResponse) => (
      isDevelopment
        ? httpProxyMiddleware(req, res, {
          // You can use the `http-proxy` option
          target: 'https://www.example.com',
          // In addition, you can use the `pathRewrite` option provided by `next-http-proxy-middleware`
          pathRewrite: [{
            patternStr: '^/api/new',
            replaceStr: '/v2'
          }, {
            patternStr: '^/api',
            replaceStr: ''
          }],
        })
        : res.status(404).send(null)
    );
    • externalResolver is an explicit flag that tells the server that this route is being handled by an external resolver. Enabling this option disables warnings for unresolved requests.
      • See the issues below

Using multipart/form-data

Contributors

Thanks goes to these wonderful people (emoji key):


Denny Lim

🐛 💻

Kristian Tryggestad

🐛 💻

Gunnlaugur Thor Briem

💻 🤔

Otto von Wesendonk

🛡️

Daniel Silva

🤔

Yann Pringault

💻

Lorenzo

📖

Timon Grassl

🐛

Abhinav Kumar

📖

Jack Cuthbert

📖

Vytenis

📖

Dario Varotto

📖

johannbrynjar

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

vscode-template

This extension makes file and folder structures easier to reuse by templating them.
JavaScript
17
star
2

winston-s3-transport

Logs generated through Winston can be transferred to an S3 bucket using `winston-s3-transport`
TypeScript
7
star
3

token-transformer-cli

Token Transformer CLI: A versatile library that enables the transformation of token information into desired forms (e.g., converting design tokens into CSS, SCSS, and more).
JavaScript
4
star
4

memoize

Memoize is a simple library that remembers the function execution results and can respond immediately.
JavaScript
4
star
5

react-suspense-render-hook

React Suspense Render Hook: This hook allows you to declaratively define components that render when asynchronous data is processed.
TypeScript
3
star
6

react-layout-boundary

By using this component, you can explicitly set layout boundaries in browser rendering to optimize performance or enhance rendering efficiency.
TypeScript
2
star
7

transformium

Transformium is a simple API proxy server implemented using Express. API proxy configuration can be applied immediately on the running server without restarting.
JavaScript
2
star
8

bithumb

A library that makes the Bithumb Exchange API easy to use.
TypeScript
1
star
9

forEach

JavaScript
1
star
10

react-hook-component-state

This hook allows you to isolate and manage the state within the component, reducing rendering operations and keeping the source code concise.
JavaScript
1
star
11

compose-hydrate-reducers

Automatically handles the HYDRATE action executed by next-redux-wrapper.
JavaScript
1
star
12

karma-outflow-preprocessor

JavaScript
1
star
13

react-render-state-hook

React Render State Hook: This hook allows you to declaratively define components that will be rendered based on the data processing state.
TypeScript
1
star
14

Xml2Json

JavaScript
1
star
15

express-socket.io-middleware

This middleware allows you to easily convert your existing HTTP REST APIs to websockets
TypeScript
1
star
16

use-transition-render

TypeScript
1
star
17

nextjs-todo-app-with-react-render-state-hook

TypeScript
1
star