Created
October 23, 2019 11:47
-
-
Save johnparn/0d0873111e7a2a8c5c12a0035a0c69b2 to your computer and use it in GitHub Desktop.
Custom server.js for NextJS in order to proxy requests to backend api
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
/** | |
* Custom server.js for NextJS in order to proxy requests to backend api | |
* | |
* Create server.js in root dir, adjust scripts in package.json | |
* | |
* "scripts": { | |
* "dev": "node server.js", | |
* "start": "NODE_ENV=production node server.js" | |
* } | |
*/ | |
const express = require('express'); | |
const proxy = require('express-http-proxy'); | |
const http = require('http'); | |
const next = require('next'); | |
const dotenv = require('dotenv'); | |
dotenv.config(); | |
const dev = process.env.NODE_ENV !== 'production'; | |
const app = next({ | |
dev, | |
}); | |
const handle = app.getRequestHandler(); | |
app.prepare().then(() => { | |
const server = express(); | |
server.use('/api/books', proxy('https://api.domain.net/v1/books')); | |
// Let NextJS handle non matching routes | |
server.get('*', handle); | |
const port = process.env.PORT || 3000; | |
http.createServer(server).listen(port, () => { | |
console.log(`> listening on port ${port} 🙌`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment