Code examples in JavaScript
These code examples have an implementation in JavaScript. To learn more about using JavaScript with our Compute 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.
Use surrogate keys to link all objects under each path prefix, allowing wildcard purging of all URLs that share a common prefix.
An implementation of Google's recommended mechanism for verifying googlebot
Decorate API responses in JSON format with new fields.
Use a transform stream to search the body of a response and replace simple template placeholders with content generated at the edge, without buffering.
Generate an invoice at the edge by rendering an HTML template with the full power of a popular template engine.
Create an API endpoint for fetching geolocation 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.
Add geolocation data about the client browser as extra headers in any requests from Fastly to your origin.
Park request, make a different request first, use the response to annotate the real origin request (or make decisions about how to route it).
Use a custom Paywall header to trigger preflight requests to authenticate every article view with a backend paywall service.
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).
Generate relative time datelines at the Edge instead of in the browser or at origin. Better caching, faster rendering, fewer reflows.
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.
Set TTLs at the edge based on looking up a path prefix in a dictionary.
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.
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.
Collect and aggregate log data submitted from browsers directly into S3 or another log store without having to handle the traffic at your origin.
Send request to different origin servers based on the URL path.
Detect specified response statuses from backends and instead serve a precomposed error page or error content generated at the edge.
Browsers send OPTIONS requests before performing cross-origin POSTs. You can answer these requests directly from the edge.
Store username/password list in a dictionary, authorize user at the edge, reject requests that don't have correct credentials.
Serve full text of robots.txt as a synthetic response to avoid requests hitting your origin.
Load balance requests randomly across multiple backends, dropping them automatically if they become unhealthy.
Map requests to backends consistently, which can be useful to improve your internal cache and replication efficiency.
Map requests to backends based on user ID (a.k.a., "sticky sessions").
Emit logging data to your chosen log endpoint from any VCL stage, not just vcl_log.
Serve binary objects, such as images, directly from edge configuration.
Make URLs expire after a configurable period.
Go from an F to an A grade on securityheaders.io by adding security policy headers to your responses at the edge.
Fastly can easily read and write HTTP headers at multiple stages of the request/response cycle.
Receive a request for one path but request a different path from origin, without a redirect.
Add, remove, and sort querystring parameters.
Change PUT, DELETE, OPTIONS and others to POST, or vice versa, to help integrate incompatible client and server apps.
Quickly fetch the user's public IP from an API endpoint on your own domain, with no origin.
Read individual cookies, set new cookies in response.
Rewrite headers to keep only keys that you want to allow, similar to `querystring.filter_except` but for headers rather than querystrings.
Treat URLs with and without suffixed slashes as equivalent, or redirect URLs with slashes to the version without.
By default, Fastly does not cache responses to POST requests. But you can enable this if you wish.
Capture regex pattern groups to use in matching url segments and more.
Block a list of IP addresses from accessing your service and include an expiry time.
Intercept suspicious traffic and display a CAPTCHA challenge. If the user passes, allow the request to go to the origin server.
Improve cache performance by normalizing requests. Filter and reorder query params, convert to lowercase, filter headers, and more.
Use regular expression substitution functions to map paths, strip extraneous slashes, and more.
Use a public GCS bucket as a backend for your Fastly service.
Use AWS compat mode to make authenticated requests to your GCS bucket.
Configure S3-compatible buckets to use as private origins for CDN delivery. Requests are authorized via signature version 4 to protect communication between your CDN service and the bucket. This is compatible with Fastly Object Storage, AWS S3, and most other S3-compatible storage offerings.
Use Microsoft Azure authenticated requests to protect communication between your Fastly service and Azure.
Build raw JSON strings matching your BigQuery table schema to send log data to BigQuery.
Access the body of a POST request in Base64-encoded form.
Generate random whole numbers in a range.
Isolate a portion of a string identified by a range of characters.
To allow caching of POST requests, consider rewriting them as GET requests at the edge.
PCI-compliant caching requires caching only in volatile storage, which you can enable with beresp.pci in VCL.
Send a copy of your traffic to a test origin before returning a response from production.
Useful for comparing capabilities with required permissions.
Detect and reject requests from third-party websites that attempt to embed your images on their pages.
When you need to work on API and text responses from backends that support gzip.
Ensure resources are not cached on the front end, while allowing caching within Fastly.
Use Fastly's support for ESI to combine multiple origin-hosted objects into a single response at the edge.
Remove headers added by backends that you don't want to emit to the browser, like amz- or goog- headers.
Protect clients from redirects by chasing them internally at the edge, and then return the eventual non-redirect response.
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.
Group countries to cache content by custom regions or reject requests from some regions entirely.
Bucket users into small grid squares to allow for hyper-local content caching (e.g., "stores near you", "local offers").
Due to ITP 2.1 restrictions, cookies set in JavaScript may be limited to a 7-day TTL. Set your Google Analytics cookie on the edge to avoid this.
If primary backend fails, retry with a different backend without caching the failure or reducing cache efficiency.
Strip the last octet or compute a hash of client IP address for anonymization.
Identify which type of IP address was used by the client connecting to your Fastly service.
Convert a password sent by the client in the querystring into a Authorization header to your origin server.
GraphQL query requests are POSTs, but responses to POST typically can't be cached. Convert it to a querystring on a GET request to allow Fastly to cache GraphQL (or any HTTP POST) request.
Unknown data in URL paths can result in invalid URLs, but base64url is designed to be URL-safe.
Block or identify syntactically invalid requests at the edge by using a hash function of your choice.
Decode the popular JWT format to verify user session tokens before forwarding trusted authentication data to your origin.
Serve different responses to separate user cohorts.
Use a dictionary of URL mappings to serve your redirects at lightning speed.
Divide the world into time bands of custom size and forward time zone data to your origin server.
Format dates and times in a variety of ways.
Match URL prefixes and make use of configurable response status and querystring preservation.
Adjust the maximum TCP socket pacing for connections at peak times of day in busy regions.
Validate your CenturyLink tokens for access to video stream playlists.
Process multiple requests in any order and still generates the same output every time. This example uses an external API to retrieve the names of 10 Star Wars characters, the logs show how the requests run in a different order every time while the output never changes (provided no request fails).
Handle third-party requests as they are resolved.
Force a response to be delivered very slowly to reduce the rate at which an attacker can send requests.
Use the `exif` Rust crate to decorate a backend response with image metadata.
Use open source libraries to dynamically serve a QR code based on query parameters.
Create a dynamic backend from the redirect response, and then get a response from the dynamic backend.
Check the query string if it contains a valid domain.
Create an HTTP API for real time backend health status
Sha256 hash a file upload and test the hash against the VirusTotal API
Remove extraneous data from PNG files created using screenshotting tools
Streaming transformations avoid buffering a response, reducing latency and memory consumption
Configure a timeout for a specific origin request, rather than relying on the configuration settings for that origin
Strips cookies and forces cross-site origin headers in requests to verify security controls and logging are working as expected.
Check for known bad bots and crawlers and deny traffic.
Check for a subdomain and rewrite the URL path.
Check for specific URL extensions and deny access with a 403.
Check for a country code on an incoming request, and if it's present, deny access with a 403.
Surrogate key purges are fast and flexible and can be used in place of single URL purge and purge-all.
If you have multiple hosting locations, Fastly can route traffic to the closest one.
Disable edge caching and skip the Fastly readthrough cache for every request, ensuring nothing is cached at the edge.
Read values from Fastly-defined env vars in Compute programs.
Backends can be defined at runtime in compute applications to make requests to any host on the internet.
Calculate the physical geo distance in kilometers between places such as the end user's location and the Fastly POP they connected to.
Use HTMLRewritingStream to rewrite an HTML payload at the edge.
All code on this page is provided under both the BSD and MIT open source licenses.
