Skip to content

Instantly share code, notes, and snippets.

@elcodabra
Last active June 22, 2020 06:19
Show Gist options
  • Save elcodabra/79959f329e564a49a927d8db51f68960 to your computer and use it in GitHub Desktop.
Save elcodabra/79959f329e564a49a927d8db51f68960 to your computer and use it in GitHub Desktop.
Next JS 9: Proxy middleware with Express
// local-server.js
const express = require('express');
const next = require('next');
const { createProxyMiddleware } = require('http-proxy-middleware');
const conf = require('./next.config');
const dev = process.env.NODE_ENV !== 'production';
const port = parseInt(process.env.PORT, 10) || 3000;
const app = next({ dev, conf });
const handler = app.getRequestHandler();
const devProxy = {
[`/${process.env.API_PATH}`]: {
target: process.env.BACKEND_API,
pathRewrite: {
[`^/${process.env.API_PATH}`] : '',
},
changeOrigin: true,
}
};
app.prepare().then(() => {
const server = express();
// Set up the proxy.
if (dev && devProxy) {
Object.keys(devProxy).forEach(context => {
server.use(createProxyMiddleware(context, devProxy[context]))
})
}
server.all('*', (req, res) => handler(req, res))
server.listen(port, (err) => {
if (err) throw err
console.info(`🚀 Ready on http://localhost:${port}`);
})
})
// next.config
module.exports = {
api: {
externalResolver: true,
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment