Web - Backend integration (API|Multi Zone)
Table of Contents
1 - About
Frontend frameworks that manage the rendering of a page need fill them with data that comes from an external API generally a Rest API.
2 - Articles Related
Possibilities | Support different host | Support same host | Description |
---|---|---|---|
Backend URL injection | Yes | Yes | cors must be relaxed on the backend |
Proxy | No | Yes | Emulate as if the backend and frontend request are served from the same host (hostname+port) |
3 - Possibilities
3.1 - Backend URL injection
Use environment variables to inject the right server host and port into your app.
React script do that by injecting them into the application via the DefinePlugin of Webpack. It allows to create global constants which can be configured at compile time.
Example:
const apiBaseUrl = process.env.NODE_ENV === 'development' ? 'localhost:3001' : '/'
3.2 - Proxy
When the front-end and the API are served from the same host, port, you can create a local proxy to redirect the HTTP request. Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.
Example of production deployment
/ - static server returns index.html with the frontend framework (React, Next, ...)
/todos - static server returns index.html with the frontend framework (React, Next, ...)
/api/todos - server handles any /api/* requests using the backend implementation
usage example: