next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Custom proxy doesn't work on getInitialProps

Open hoangdv1995 opened this issue 8 years ago • 1 comments

Hi all, I want to customize http://localhost:3000/api/ to http://api.example/api/. I've referenced https://github.com/zeit/next.js/tree/canary/examples/with-custom-reverse-proxy but it does not work on getInitialProps.

// server.js
const next = require('next');
const routes = require('./routes');
const proxyMiddleware = require('http-proxy-middleware');

const devProxy = {
  '/api/**': {
    target: 'http://api.example/',
    changeOrigin: true,
  }
};

const port = 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dir: '.', dev});
const handle = routes.getRequestHandler(app);

const express = require('express');
app.prepare()
  .then(() => {
    const server = express();
    if (dev && devProxy) {
      Object.keys(devProxy).forEach(function (context) {
        server.use(proxyMiddleware(context, devProxy[context]))
      });
    }
    server.all('*', (req, res) => handle(req, res));
    server.listen(port, (err) => {
      if (err) throw err;
      console.log(`> Ready on http://localhost:${port}`)
    })
  })
  .catch(err => {
    console.log('An error occurred, unable to start the server');
    console.log(err);
  })
;

Thanks!

hoangdv1995 avatar Jul 03 '18 09:07 hoangdv1995

Questions should be posted on https://spectrum.chat/next-js.

timneutkens avatar Jul 03 '18 10:07 timneutkens