Using Nuxt to develop a universal JS app, I'm attempting to configure webpack's dev proxy so that, in development only, requests to /api
get proxied to http://127.0.0.1:500/api
where they'll reach a Python REST API. Following the Nuxt docs, I've extended the webpack config in nuxt.config.js
like so:
build: {
extend (config, { isDev }) {
// Proxy /api to Python only in dev
if (isDev) {
const devServer = {
proxy: {
'/api': 'http://127.0.0.1:5000'
}
}
config.devServer = devServer;
}
}
}
If I log the config, I see that change being applied:
...
devServer: { proxy: { '/api': 'http://127.0.0.1:5000' } } }
...
Yet, when I visit http://127.0.0.1:8080/api/things, my Nuxt app is returned (it runs on port 8080 in dev), indicating that the webpack dev proxy is not catching the /api
path and performing the proxying. Just to confirm that the proxy destination is working, if I visit http://127.0.0.1:5000/api/things, I get the expected API response. Why, when I've extended the Nuxt webpack config to enable the webpack dev proxy, does the proxy not function?
I have, however, had success with the @nuxt/proxy module, but critically, I could not find a way to make it only affect development and not production. That portion of nuxt.config.js
looked like this:
axios: {
proxy: true
},
proxy: {
'/api': 'http://127.0.0.1:5000'
},
I'm happy to use the @nuxt/proxy module instead of (on top of?) the webpack dev proxy if it can be made to work in development only.
I needed to do this and was able to solve this using the following in nuxt.config.js
export default {
// other config ...
...process.env.NODE_ENV === 'development' && {
proxy: {
'/api': 'http://localhost:8000',
}
},
}
This code will only add the proxy key in the nuxt config if we're doing a development build.
Reference to the syntax used to insert the conditional object field (this was previously unknown to myself): https://stackoverflow.com/a/51200448
Ugh, I'm barking up the wrong tree.
Nuxt needs to proxy, even in production. When my initial request is processed and the app is server-side-rendered, any API requests need to be proxied because the Node server is doing the calling, not a browser, so those API requests won't even hit my production router like nginx or HAProxy (which typically does my routing for /
and /api
to the appropriate services).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With