The final portion of this section deals with proxying API requests, which involves customizing the Gatsby configuration file. Many Gatsby developers employ an architectural approach that involves hosting the backend server implementation and frontend React application from the same host and port, which can lead to issues when sourcing data for presentation in Gatsby, as some source plugins expect distinct hostnames or ports.
To mitigate this problem, Gatsby’s development server can be instructed through configuration to proxy any unknown incoming requests to the API server during development with the proxy
field in gatsby-config.js. The proxy
field accepts a single object or an array of objects, as the following example demonstrates:
// gatsby-config.js
module.exports
=
{
proxy:
[
{
prefix:
"/api",
},
{
prefix:
"/api2",
},
],
}
When performing data retrieval in development, Gatsby’s development server recognizes that rather than being a request for a static asset, the request is for API data. As such, Gatsby will then proxy the API request to the designated fallback as set in the Gatsby configuration file.
NOTE
The proxy configuration in Gatsby takes effect only in the development server and has no effect in production. For more information about advanced proxying use cases like adding middleware with the developMiddleware
option and self-signed certificates, consult the Gatsby documentation’s guide to advanced proxying.
Leave a Reply