1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/with-custom-reverse-proxy/server.es6.js
Tran Dac Anh c87b471b22 Example to add custom reverse proxy like in webpack-dev-server (#2660)
* add with-custom-reverse-proxy example

* cleanup

* cleanup package.json

* fix linting errors

* more linting errors
2017-07-29 14:45:12 +02:00

51 lines
1.1 KiB
JavaScript

/* eslint-disable no-console */
import express from 'express'
import next from 'next'
const devProxy = {
'/api': {
target: 'https://swapi.co/api/',
pathRewrite: {'^/api': '/'},
changeOrigin: true
}
}
const port = process.env.PORT || 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)
})