Proxy to backend with default Next.js dev server
Solution 1
There is now an official feature for this in the config: Rewrites
Besides normal path rewrites, they can also proxy requests to another webserver
next.config.js:
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:8000/:path*' // Proxy to Backend
}
]
}
}
Solution 2
My server.js set up, hope it helps
import express from 'express';
import next from 'next';
import proxy from 'http-proxy-middleware';
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(
'/api',
proxy({
target: process.env.API_HOST,
changeOrigin: true,
}),
);
server.all('*', (req, res) => handle(req, res));
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.js
"scripts": {
"dev": "NODE_ENV=development node -r esm server.js",
"build": "NODE_ENV=production next build",
"start": "NODE_ENV=production node -r esm server.js",
},
Solution 3
Rewrites didn't work for me, and neither did using axios config.proxy
.
I've resorted to a good old constant:
const SERVER_URL =
process.env.NODE_ENV === 'production' ? 'https://produrl.com : 'http://localhost:8000';
export async function getStaticProps() {
const data = axios.get(`${SERVER_URL}/api/my-route`)
// ...
}
I would much rather proxy requests and keep my requests cleaner, but I don't have a day to spend wrestling with this.
Maybe this very simple setup will help others.
Related videos on Youtube
cclloyd
Updated on February 25, 2021Comments
-
cclloyd about 3 years
Before, when I made apps with create-react-app, I would have a
setupProxy.js
file that would route API requests similar to thisconst proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use('/api', proxy({ target: 'http://localhost:8000', changeOrigin: true, }) ); };
But that doesn't seem to work with next.js. When I do the same thing, I get various errors.
Googling a solution, a lot say to use a custom server of some kind. But how would I accomplish a proxy like above using the default nextjs dev server? (Equivalent of
npm run dev
whendev
in my package.json isnext dev
. -
iamhuynq about 4 years
NODE_ENV=development node -r esm server.js
-
Germa Vinsmoke over 3 yearsIf using
require
thenconst { createProxyMiddleware } = require('http-proxy-middleware');
-
christopherbalz over 3 yearsimport { createProxyMiddleware } from 'http-proxy-middleware';
-
cdaringe over 3 yearsalso, i did
node server.mjs
and dropped all of the ESM custom malarkey. node 15 plays nicely w/ esm in mjs files :) -
nemish zalavadiya neel about 3 yearsthis one is not working when i want WebSocket proxy. it's handshake is failing.
-
Marnix.hoh about 3 years@nemishzalavadiyaneel socket.io doesn't work for me either using rewrites... Were you able to find a solution that does not involve creating a custom server?
-
nemish zalavadiya neel about 3 yearsI still do not. I am creating
const
object and storing hardcoded URL there. share it if you find any solution. -
Julian Mendez almost 3 yearshihi, did you do this? I did ti and the build/nodemon was too long
-
Alan Yong almost 3 yearsI believe
Rewrites
just basic proxy setup. More proxy configuration need to setup custom server -
Daniel over 2 yearsIncase anyone is handling this in their nginx config in production here is how to make config options development only. nextjs.org/docs/api-reference/next.config.js/introduction