Table of Contents

About

Frontend frameworks that manage the rendering of a page need to fill them with data that comes from an external API generally a Rest API.

Possibilities Support different host Support same host Description
Environment variables only Yes Yes cors must be relaxed on the backend
Proxy No Yes Emulate as if the backend and frontend requests are served from the same host (hostname+port)

Possibilities

Environment variables

You can use environment variables to inject the right configuration at build time.

Example:

  • With Javascript, all building engine set the node env variable to define the target environment. For example to inject a server host and port into your app.
const apiBaseUrl = process.env.NODE_ENV === 'development' ? 'localhost:3001' : '/'
  • Your building engine also allows injecting environment variables, check their documentation

HTTP Proxy

You can create a local proxy to redirect the HTTP request to your API HTTP server. You stay on the same origin and you avoid the cross-origin mechanism.

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

All building engine allows the configuration of a proxy with their development server, check their documentation. Example:

In production, see Proxy implementation