next.js
next.js copied to clipboard
Custom proxy doesn't work on getInitialProps
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!
Questions should be posted on https://spectrum.chat/next-js.