Proxy to backend with default Next.js dev server

37,744

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

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.

Share:
37,744

Related videos on Youtube

cclloyd
Author by

cclloyd

Updated on February 25, 2021

Comments

  • cclloyd
    cclloyd about 3 years

    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');
    module.exports = function(app) {
        app.use('/api',
            proxy({
                target: 'http://localhost:8000',
                changeOrigin: true,
            })
        );
    };
    

    But that doesn't seem to work with next.js. When I do the same thing, I get various errors.

    Googling a solution, a lot say to use a custom server of some kind. But how would I accomplish a proxy like above using the default nextjs dev server? (Equivalent of npm run dev when dev in my package.json is next dev.

  • iamhuynq
    iamhuynq about 4 years
    NODE_ENV=development node -r esm server.js
  • Germa Vinsmoke
    Germa Vinsmoke over 3 years
    If using require then const { createProxyMiddleware } = require('http-proxy-middleware');
  • christopherbalz
    christopherbalz over 3 years
    import { createProxyMiddleware } from 'http-proxy-middleware';
  • cdaringe
    cdaringe over 3 years
    also, i did node server.mjs and dropped all of the ESM custom malarkey. node 15 plays nicely w/ esm in mjs files :)
  • nemish zalavadiya neel
    nemish zalavadiya neel about 3 years
    this one is not working when i want WebSocket proxy. it's handshake is failing.
  • Marnix.hoh
    Marnix.hoh about 3 years
    @nemishzalavadiyaneel socket.io doesn't work for me either using rewrites... Were you able to find a solution that does not involve creating a custom server?
  • nemish zalavadiya neel
    nemish zalavadiya neel about 3 years
    I still do not. I am creating const object and storing hardcoded URL there. share it if you find any solution.
  • Julian Mendez
    Julian Mendez almost 3 years
    hihi, did you do this? I did ti and the build/nodemon was too long
  • Alan Yong
    Alan Yong almost 3 years
    I believe Rewrites just basic proxy setup. More proxy configuration need to setup custom server
  • Daniel
    Daniel over 2 years
    Incase anyone is handling this in their nginx config in production here is how to make config options development only. nextjs.org/docs/api-reference/next.config.js/introduction