npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-http-proxy-middleware

v1.2.6

Published

Nextjs HTTP Proxy Middleware

Downloads

194,483

Readme

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)

  • This function is supported by Next.js. No additional libraries need to be installed!
    • https://nextjs.org/docs/api-reference/next.config.js/rewrites
    // next.config.js
    async rewrites() {
     return [
       {
         source: "/api/:path*",
         destination: "http://example.com/api/:path*",
       },
     ];
    },

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.

    import type { NextApiRequest, NextApiResponse } from "next";
    import type { NextHttpProxyMiddlewareOptions } from "next-http-proxy-middleware";
    import httpProxyMiddleware from "next-http-proxy-middleware";
    
    const handleProxyInit: NextHttpProxyMiddlewareOptions["onProxyInit"] = (proxy) => {
      /**
      * 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
    import type { NextApiRequest, NextApiResponse } from "next";
    import httpProxyMiddleware from "next-http-proxy-middleware";
    
    const isDevelopment = process.env.NODE_ENV !== "production";
    
    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
        • https://github.com/stegano/next-http-proxy-middleware/issues/32
        • https://github.com/stegano/next-http-proxy-middleware/issues/21

Using multipart/form-data

  • If you are using the multipart/form-data, refer to the Issues below
    • https://github.com/stegano/next-http-proxy-middleware/issues/33
    • https://github.com/vercel/next.js/pull/7686

Contributors ✨

Thanks goes to these wonderful people (emoji key):

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