Skip to content Skip to sidebar Skip to footer

Proxy To Backend With Default Next.js Dev Server

Before, when I made apps with create-react-app, I would have a setupProxy.js file that would route API requests similar to this const proxy = require('http-proxy-middleware'); modu

Solution 1:

There is now an official feature for this in the config: Rewrites

Besides normal path rewrites, they can also proxy requests to another webserver

next.config.js:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:8000/:path*' // Proxy to Backend
      }
    ]
  }
}

See Next.js Docs Rewrites


Solution 2:

My server.js set up, hope it helps

import express from 'express';
import next from 'next';
import proxy from 'http-proxy-middleware';

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    const server = express();

    server.use(
        '/api',
        proxy({
            target: process.env.API_HOST,
            changeOrigin: true,
        }),
    );

    server.all('*', (req, res) => handle(req, res));

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
});

package.js

"scripts": {
    "dev": "NODE_ENV=development node -r esm server.js",
    "build": "NODE_ENV=production next build",
    "start": "NODE_ENV=production node -r esm server.js",
},

Solution 3:

Ended up using something similar to what was posted. Used config files from here

https://github.com/zeit/next.js/tree/master/examples/with-custom-reverse-proxy


Solution 4:

Rewrites didn't work for me, and neither did using axios config.proxy.

I've resorted to a good old constant:

const SERVER_URL = 
  process.env.NODE_ENV === 'production' ? 'https://produrl.com : 'http://localhost:8000';

export async function getStaticProps() {
  const data = axios.get(`${SERVER_URL}/api/my-route`)
  // ...
}

I would much rather proxy requests and keep my requests cleaner, but I don't have a day to spend wrestling with this.

Maybe this very simple setup will help others.


Post a Comment for "Proxy To Backend With Default Next.js Dev Server"