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).
Best to use an environment variable, there's an example for that (with-universal-configuration). From what I can see there is an option to provide a basePath to Axios: https://github.com/mzabriskie/axios#axioscreateconfig
@timneutkens
Hi thanks!
I used technique Rauch suggested in other issue by reading environment variable from getInitialProps and then I would set variable at the window object which I would use in axios urls. I am looking for solution that would avoid DRY as much as possible. I will see if it's possible to configure axios instance from within getInitialProps otherwise current workaround will do.
This thread has been automatically locked because it has not had recent activity. Please open a new issue for related bugs and link to relevant comments in this thread.
Most helpful comment
Best to use an environment variable, there's an example for that (with-universal-configuration). From what I can see there is an option to provide a basePath to Axios: https://github.com/mzabriskie/axios#axioscreateconfig