I am using Next.js
and Axios
libraries.
My axios requests look like this:
axios.get('/api/users/1')
This worked while I had API and rendering server inside same instance. But now my API backend is fully separated.
While in dev mode, it is hosted at localhost:3001
while frontend (next) dev server is hosted on localhost:3000
. In production rendering server is hosted at https://example.com
while API is hosted at https://api.someoherdomain.com
.
How to keep axios requests clean (without importing stuff and prefixing url string by hand), keeping them like /api/users/1
but automactially making them localhost:3000/api/users/1
while running development mode and https://example.com/api/users/1
while hosted in production.
I need something like https://github.com/zeit/next.js/tree/master/examples/with-custom-reverse-proxy but to work on both production and development mode.
Not a recommended approach to production scale (hence explicit dev flag) as we should scope proxy as outside UI applications and have separate web server taking care of that.
If this is not possible, I am looking for the most elegant way to handle this. Any suggestions?
In production we use Plesk (which uses Ngnix).
You could create an axios
instance and set the baseUrl
parameter based on a environment variable :)
Documentation here: https://github.com/mzabriskie/axios#creating-an-instance