- Newest
- Most votes
- Most comments
Unfortunately, it's not possible to directly add CloudFront Viewer location headers like CloudFront-Viewer-Latitude, CloudFront-Viewer-Longitude, and CloudFront-Viewer-Time-Zone to an Edge-Optimized API Gateway. Edge-Optimized API Gateways are already integrated with CloudFront, but they don't provide access to these specific geolocation headers.
However, you can achieve your goal by using a combination of CloudFront and a Regional API Gateway. Here's a recommended approach:
-
Create a Regional API Gateway instead of an Edge-Optimized one.
-
Set up a CloudFront distribution in front of your Regional API Gateway. This allows you to leverage CloudFront's geolocation capabilities.
-
Create an Origin Request Policy for your CloudFront distribution. In this policy, include the headers you need: CloudFront-Viewer-Country and CloudFront-Viewer-Country-Region. Unfortunately, CloudFront doesn't provide direct latitude, longitude, or time zone headers, but you can use these country and region headers as a starting point.
-
Attach this Origin Request Policy to the behavior in your CloudFront distribution that routes requests to your API Gateway.
-
In your Lambda functions, you can now access these headers from the event object. You'll need to implement logic to map the country and region information to more specific latitude, longitude, and time zone data if required.
-
To avoid caching issues, make sure to configure your CloudFront distribution and API Gateway caching settings appropriately. You may need to disable caching or set up cache keys based on the relevant headers and request parameters.
By using this setup, you can maintain the performance benefits of an edge-optimized setup while also gaining access to geolocation information. Your API calls will be routed through CloudFront's global network to the nearest edge location, and then to your Regional API Gateway, providing a similar experience to an Edge-Optimized API Gateway.
Remember that while this approach doesn't provide exact latitude and longitude, it gives you country and region information, which can be used as a basis for approximating location in many use cases. If you need more precise location data, you might need to consider alternative methods, such as using a third-party geolocation service or having the client send location information directly.
Sources
How do I make CloudFront request headers available in my edge compute functions? | AWS re:Post
Community | Serverless statistics solution with Lambda@Edge
Relevant content
asked 10 months ago
- AWS OFFICIALUpdated 10 months ago
