Code examples in JavaScript
These code examples have an implementation in JavaScript. To learn more about using JavaScript with our Compute@Edge platform, see using JavaScript.
NOTE: Some of the code examples here are also available in languages other than JavaScript. Being able to see how the same solution can be achieved in other languages is often useful for migrations or learning, so where a code example has multiple implementations, we show all implementations together.
Add a new field to a JSON response
Decorate API responses in JSON format with new fields.
Geo-IP API at the edge
Create an API endpoint for fetching GeoIP data for the requesting browser, implemented 100% at the edge. The response should show your current approximate location, but no requests to any origin servers.
Tag requests with geolocation data
Add GeoIP data about the client browser as extra headers in any requests from Fastly to your origin.
Apply feature flags from an origin API
Park request, make a different request first, use the response to annotate the real origin request (or make decisions about how to route it).
Detect leaked passwords
Detect requests that contain submitted passwords and use a service to determine whether the password has leaked before allowing the request to proceed to origin (data from haveibeenpwned).
Add www. to apex hostname and subdomains
Detect requests that don't include a www. prefix, and redirect to the equivalent path on a hostname that starts with www., usually to make sure there's only one canonical location for your content.
Override TTLs for path prefixes
Set TTLs at the edge based on looking up a path prefix in an edge dictionary.
Push prices or breaking news in real time with Server-Sent-Events
Stream responses to the browser while still receiving data from the origin and also saving it to cache. Great for spreading out server-sent-events streams to millions of users from a single source stream.
Map IPv6 addresses to IPv4 address space
Create an identifier that looks like an IPv4 address if the user has made their request using IPv6. Useful for origin servers that require an IPv4 address for some reason.
Capture and aggregate log data from client devices
Collect and aggregate log data submitted from browsers directly into S3 or another log store without having to handle the traffic at your origin.
Use microservices to divide up a domain
Send request to different origin servers based on the URL path.
Answer CORS OPTIONS preflight requests at the edge
Browsers send OPTIONS requests before performing cross-origin POSTs. You can answer these requests directly from the edge.
Apply HTTP basic auth to private endpoints
Store username/password list in an edge dictionary, authorize user at the edge, reject requests that don't have correct credentials.
Load balance randomly across multiple backends
Load balance requests randomly across multiple backends, dropping them automatically if they become unhealthy.
Load balance to optimise upstream caching with hash directors
Map requests to backends consistently, which can be useful to improve your internal cache and replication efficiency.
Sticky sessions using client directors
Map requests to backends based on user ID (a.k.a., "sticky sessions").
Enable modern web security headers to all responses
Go from an F to an A grade on securityheaders.io by adding security policy headers to your responses at the edge.
Add, remove or change HTTP headers
Fastly can easily read and write HTTP headers at multiple stages of the request/response cycle.
Filter query string parameters
Add, remove, and sort querystring parameters.
Change request method
Change PUT, DELETE, OPTIONS and others to POST, or vice versa, to help integrate incompatible client and server apps.
Client public IP API at the edge
Quickly fetch the user's public IP from an API endpoint on your own domain, with no origin.
Add or remove cookies
Read individual cookies, set new cookies in response.
Apply CAPTCHA to high risk requests
Intercept suspicious traffic and display a CAPTCHA challenge. If the user passes, allow the request to go to the origin server.
Normalize requests to increase cache efficiency
Improve cache performance by normalizing requests. Filter and reorder query params, convert to lowercase, filter headers, and more.
Search and replace in strings
Use regular expression substitution functions to map paths, strip extraneous slashes, and more.
Google Cloud Storage origin (public)
Use a public GCS bucket as a backend for your Fastly service.
Google Cloud Storage origin (private)
Use AWS compat mode to make authenticated requests to your GCS bucket.
AWS S3 bucket origin (private)
Use AWS authenticated requests (signature version 4) to protect communication between your Fastly service and AWS.
Azure blob storage bucket origin (private)
Use Microsoft Azure authenticated requests to protect communication between your Fastly service and Azure.
Base64 POST body
Access the body of a POST request in Base64-encoded form.
Extract a substring from a string value
Isolate a portion of a string identified by a range of characters.
POST to GET rewrite using a Base64-encoded querystring
To allow caching of POST requests, consider rewriting them as GET requests at the edge.
Clean backend responses
Remove headers added by backends that you don't want to emit to the browser, like amz- or goog- headers.
Remove querystring from static assets
Use the new Sec-Fetch-Dest header or URL patterns to identify assets that should not allow querystrings to be part of the cache key.
Auto retry a secondary backend
If primary backend fails, retry with a different backend without caching the failure or reducing cache efficiency.
Anonymize client IPs for logging
Strip the last octet or compute a hash of client IP address for anonymization.
Base64 URL path segments
Unknown data in URL paths can result in invalid URLs, but base64url is designed to be URL-safe.
Check validity of inputs using a non-crypto hash
Block or identify syntactically invalid requests at the edge by using a hash function of your choice.
Redirect old URLs at the edge
Use a dictionary of URL mappings to serve your redirects at lightning speed.
Perform multiple origin requests asynchronously
Handle third-party requests as they are resolved.
All code on this page is provided under both the BSD and MIT open source licenses.