Last active
June 22, 2020 06:19
-
-
Save elcodabra/79959f329e564a49a927d8db51f68960 to your computer and use it in GitHub Desktop.
Next JS 9: Proxy middleware with Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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}`); | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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