title: How to HTTP proxy for Next.js API requests
body: <p>I have tried lots of things online but nothing is working so far.</p>
  <h2>First try (<code>src/pages/api/proxy/[...slug].js</code>):</h2>
  <pre><code>import { createProxyMiddleware } from 'http-proxy-middleware';
  
  // Create proxy instance outside of request handler function to avoid unnecessary re-creation
  const apiProxy = createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
      pathRewrite: { [`^/api/proxy`]: '' },
      secure: false,
  });
  
  export default function (req, res) {
      apiProxy(req, res, (result) =&gt; {
          if (result instanceof Error) {
              throw result;
          }
  
          throw new Error(`Request '${req.url}' is not proxied! We should never reach here!`);
      });
  };
  </code></pre>
  <p>Gives me errors like:</p>
  <pre><code>TypeError: Object(...) is not a function
      at Module../pages/api/[...slug].js (/home/user/app/client/.next/server/pages/api/[...slug].js:109:101)
      at __webpack_require__ (/home/user/app/client/.next/server/pages/api/[...slug].js:23:31)
      at /home/user/app/client/.next/server/pages/api/[...slug].js:91:18
      at Object.&lt;anonymous&gt; (/home/user/app/client/.next/server/pages/api/[...slug].js:94:10)
      at Module._compile (node:internal/modules/cjs/loader:1092:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
      at Module.load (node:internal/modules/cjs/loader:972:32)
      at Function.Module._load (node:internal/modules/cjs/loader:813:14)
      at Module.require (node:internal/modules/cjs/loader:996:19)
      at require (node:internal/modules/cjs/helpers:92:18)
      at DevServer.handleApiRequest (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:64:181)
      at runMicrotasks (&lt;anonymous&gt;)
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async Object.fn (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:56:492)
      at async Router.execute (/home/user/app/client/node_modules/next/dist/next-server/server/router.js:23:67)
      at async DevServer.run (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:66:1042)
  </code></pre>
  <h2>Second try (<code>next.config.js</code>):</h2>
  <pre><code>module.exports = {
      async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'http://localhost:5000/:path*' // Proxy to Backend
          }
        ]
      }
    }
  </code></pre>
  <p>This thing is not working at all.</p>
  <h2>Third try (with <a href="https://www.npmjs.com/package/next-http-proxy-middleware" rel="nofollow noreferrer"><code>next-http-proxy-middleware</code></a>):</h2>
  <pre><code>// pages/[...all].ts
  ...
  export default (req: NextApiRequest, res: NextApiResponse) =&gt; (
    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`
        pathRewrite: {
          '^/api/new': '/v2',
          '^/api': '',
        },
      })
      : res.status(404).send(null)
  );
  </code></pre>
  <p>This thing has no documentation at all... have no idea how it works.</p>
  <h2>Fourth try (with a <a href="https://nextjs.org/docs/advanced-features/custom-server" rel="nofollow noreferrer">custom Next server</a>):</h2>
  <pre><code>const express = require('express')
  const next = require('next')
  const { createProxyMiddleware } = require(&quot;http-proxy-middleware&quot;)
  
  const port = process.env.PORT || 3000
  const dev = process.env.NODE_ENV !== 'production'
  const app = next({ dev })
  const handle = app.getRequestHandler()
  
  const apiPaths = {
      '/api': {
          target: 'http://localhost:3080', 
          pathRewrite: {
              '^/api': '/api'
          },
          changeOrigin: true
      }
  }
  
  const isDevelopment = process.env.NODE_ENV !== 'production'
  
  app.prepare().then(() =&gt; {
    const server = express()
   
    if (isDevelopment) {
      server.use('/api', createProxyMiddleware(apiPaths['/api']));
    }
  
    server.all('*', (req, res) =&gt; {
      return handle(req, res)
    })
  
    server.listen(port, (err) =&gt; {
      if (err) throw err
      console.log(`&gt; Ready on http://localhost:${port}`)
    })
  }).catch(err =&gt; {
      console.log('Error:::::', err)
  })
  </code></pre>
  <p>This runs express inside next app.
  I needed the next app and the server to be separated. This is just not what I wanted.</p>