Created
February 4, 2020 04:50
-
-
Save HaiBV/3f83f0bf189e00fae1fd9aeb064cf582 to your computer and use it in GitHub Desktop.
Custom Reverse Proxy
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
/* eslint-disable no-console */ | |
const express = require('express') | |
const next = require('next') | |
const devProxy = { | |
'/api': { | |
target: 'https://swapi.co/api/', | |
pathRewrite: { '^/api': '/' }, | |
changeOrigin: true, | |
}, | |
} | |
const port = parseInt(process.env.PORT, 10) || 3000 | |
const env = process.env.NODE_ENV | |
const dev = env !== 'production' | |
const app = next({ | |
dir: '.', // base directory where everything is, could move to src later | |
dev, | |
}) | |
const handle = app.getRequestHandler() | |
let server | |
app | |
.prepare() | |
.then(() => { | |
server = express() | |
// Set up the proxy. | |
if (dev && devProxy) { | |
const proxyMiddleware = require('http-proxy-middleware') | |
Object.keys(devProxy).forEach(function(context) { | |
server.use(proxyMiddleware(context, devProxy[context])) | |
}) | |
} | |
// Default catch-all handler to allow Next.js to handle all other routes | |
server.all('*', (req, res) => handle(req, res)) | |
server.listen(port, err => { | |
if (err) { | |
throw err | |
} | |
console.log(`> Ready on port ${port} [${env}]`) | |
}) | |
}) | |
.catch(err => { | |
console.log('An error occurred, unable to start the server') | |
console.log(err) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment