Code examples
Our code examples library is an always-evolving set of samples to do just about anything on the Fastly edge cloud. Browse or search for a keyword to find the perfect, ready-made solution you can paste into your service or adapt and customize for your own needs. Using Fastly Fiddle, play with any example and take advantage of the Fastly edge cloud, all without registering or affecting any existing account.
Verify if a web crawler accessing your server really is Googlebot
An implementation of Google's recommended mechanism for verifying googlebot
SEOResponse manipulation
Add a new field to a JSON response
Decorate API responses in JSON format with new fields.
Response manipulation
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.
GeolocationResponse manipulationPerformance
Tag requests with geolocation data
Add GeoIP data about the client browser as extra headers in any requests from Fastly to your origin.
GeolocationRequest manipulationDeveloper experience
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).
FetchRequest manipulationCachePersonalization
Enforce a paywall using an origin API
Use a custom Paywall header to trigger preflight requests to authenticate every article view with a backend paywall service.
FetchRequest manipulationCacheSecurity
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).
FetchRequest manipulationCacheSecurity
Convert timestamps to relative times like '2 hours ago'
Generate relative time datelines at the Edge instead of in JavaScript or at origin. Better caching, faster rendering, fewer reflows.
Response manipulationESIPerformance
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.
Request manipulationCacheDeveloper experience
Serve stale to search crawlers for better ranking
Prioritize human traffic over search crawlers by serving stale content to crawlers.
CacheResponse manipulationSEO
Support caching of OPTIONS requests
Normally OPTIONS requests aren't cacheable. Allow caching of OPTIONS by converting the request to a GET and back to OPTIONS if it's a cache miss.
CachePerformance
Override TTLs based on content type
Set TTLs at the edge based on the type of resource. Better done at origin, but this can be a great 'quick fix' or a solution if you don't control the origin.
CachePerformance
Override TTLs for path prefixes
Set TTLs at the edge based on looking up a path prefix in an edge dictionary.
CachePerformance
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.
CacheResponse manipulationPerformance
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.
LoggingObservability
Use microservices to divide up a domain
Send request to different origin servers based on the URL path.
BackendsPerformance
Replace origin errors with 'safe' responses
Detect specified response statuses from backends and instead serve a precomposed error page or error content generated at the edge.
Response manipulationErrorsCacheResilience
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.
Response manipulationPerformance
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.
Request manipulationEdge dataSecurity
Serve robots.txt from the edge
Serve full text of robots.txt as a synthetic response to avoid requests hitting your origin.
Response manipulationEdge dataSEO
Serve stale content from cache while origins are offline
Deal with all potential scenarios for using stale content to satisfy requests when origin is unhealthy or misbehaving.
Response manipulationCacheResilience
Load balance randomly across multiple backends
Load balance requests randomly across multiple backends, dropping them automatically if they become unhealthy.
BackendsPerformance
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.
BackendsPerformance
Cycle through backends until a healthy server is found
Try backends in turn until one is healthy (also known as an 'active-standby' strategy).
BackendsPerformance
Sticky sessions using client directors
Map requests to backends based on user ID (a.k.a., "sticky sessions").
BackendsPerformance
Log the data you need for actionable insights
Emit logging data to your chosen log endpoint from any VCL stage, not just vcl_log.
BackendsPerformance
Support video scrubbing or download resumption using Range requests
Range headers sent from client are stripped by Fastly so we can cache the full object at the edge.
Serve small binary assets direct from edge
Serve binary objects, such as images, directly from edge configuration.
Response manipulationPerformance
Make very large payloads visible in VCL using custom headers
Using the Fetch API in JavaScript, it's possible to add custom headers to a request and see that data in VCL, which is subject to a much higher limit than those that we place on URL length and exposed POST body.
Create self-destructing URLs for time-limited access
Make URLs expire after a configurable period.
Request manipulationEdge dataSecurity
Transform and optimize images on the fly
Use Fastly Image Optimizer to transform and serve images at the edge, closer to your users.
Image optoPerformance
Schedule a cache invalidation at a predefined time
Purge your edge cache automatically at a certain time. This may cause an inrush of traffic to origin at the scheduled time and should be used with care.
CachePerformance
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.
Response manipulationSecurity
Configuration version discrepancy detection
Detect situations when a shield server might have a different version of your code than the edge server, and avoid errors that this might cause.
Add, remove or change HTTP headers
Fastly can easily read and write HTTP headers at multiple stages of the request/response cycle.
Request manipulationResponse manipulationDeveloper experience
Rewrite URL path
Receive a request for one path but request a different path from origin, without a redirect.
Request manipulationDeveloper experience
Filter query string parameters
Add, remove, and sort querystring parameters.
Request manipulationCachePerformance
Change request method
Change PUT, DELETE, OPTIONS and others to POST, or vice versa, to help integrate incompatible client and server apps.
Request manipulation
Compress content before caching
Compress HTML, SVG, and other compressible formats at the edge and store and serve both compressed and uncompressed versions.
CompressionPerformance
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.
Response manipulationDeveloper experience
Add or remove cookies
Read individual cookies, set new cookies in response.
Request manipulationResponse manipulationPerformance
Filter cookies or other structured headers
Rewrite headers to keep only keys that you want to allow, similar to `querystring.filter_except` but for headers rather than querystrings.
Request manipulationResponse manipulationSecurity
Remove trailing slashes to normalize URLs
Treat URLs with and without suffixed slashes as equivalent, or redirect URLs with slashes to the version without.
Request manipulationCachePerformance
Caching responses to POST requests
By default, Fastly does not cache responses to POST requests. But you can enable this if you wish.
CachePerformance
Regular expression capturing patterns
Capture regex pattern groups to use in matching url segments and more.
Ban bad IPs for a fixed period
Block a list of IP addresses from accessing your service and include an expiry time.
Response manipulationEdge dataSecurity
ACL based IP block list
Block a list of IP address ranges from accessing your service.
Response manipulationEdge dataSecurity
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.
Response manipulationRequest manipulationFetchBackendsEdge dataSecurity
Normalize requests to increase cache efficiency
Improve cache performance by normalizing requests. Filter and reorder query params, convert to lowercase, filter headers, and more.
Request manipulationCachePerformance
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.
Request manipulationResponse manipulationEdge dataPerformance
Google Cloud Storage origin (private)
Use AWS compat mode to make authenticated requests to your GCS bucket.
Request manipulationResponse manipulationEdge dataSecurity
AWS S3 bucket origin (private)
Use AWS authenticated requests (signature version 4) to protect communication between your Fastly service and AWS.
Request manipulationResponse manipulationEdge dataSecurity
Azure blob storage bucket origin (private)
Use Microsoft Azure authenticated requests to protect communication between your Fastly service and Azure.
Request manipulationResponse manipulationEdge dataSecurity
Alibaba Object Storage Service origin (private)
Use authenticated requests to protect communication between your Fastly service and Alibaba's Object Storage Service.
Request manipulationResponse manipulationEdge dataSecurity
Log request data to Google BigQuery
Build raw JSON strings matching your BigQuery table schema to send log data to BigQuery.
LoggingObservability
Support matching on unicode in VCL. すごい!
Represent non-ASCII characters in VCL using unicode escapes.
Base64 POST body
Access the body of a POST request in Base64-encoded form.
Random integers
Generate random whole numbers in a range.
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.
Request manipulation
Set PCI flag to disable persistent cache storage
PCI-compliant caching requires caching only in volatile storage, which you can enable with beresp.pci in VCL.
CacheSecurity
Early expiry of cached objects
Cached a large number of objects for too long and want to update and shorten their TTLs.
CachePerformance
Smoke test a new origin
Send a copy of your traffic to a test origin before returning a response from production.
Request manipulationBackendsResilience
Compute intersection of two lists
Useful for comparing capabilities with required permissions.
Prevent hotlinking of product images by third party websites
Detect and reject requests from third party websites that attempt to embed your images on their pages.
Response manipulationSecurity
Decompress and read gzipped responses
When you need to work on API and text responses from backends that support gzip.
CompressionResponse manipulationDeveloper experience
Prohibit browser caching
Ensure resources are not cached on the front end, while allowing caching within Fastly.
Response manipulationPerformance
Assemble content at the edge with Edge-side includes (ESI)
Use Fastly's support for ESI to combine multiple origin-hosted objects into a single response at the edge.
ESIResponse manipulationPerformance
Clean backend responses
Remove headers added by backends that you don't want to emit to the browser, like amz- or goog- headers.
Response manipulationDeveloper experience
Redirect insecure HTTP to TLS (SSL, HTTPS) in VCL
Redirect any requests that come in on insecure HTTP, to the equivalent TLS endpoint.
Response manipulationSecurity
Follow redirects at the edge
Protect clients from redirects by chasing them internally at the edge, and then return the eventual non-redirect response.
FetchResponse manipulationDeveloper experience
Cache '429' rate-limiter responses per IP
If a backend returns a 429, cache it for the requesting IP but continue to allow other clients to use origin.
Request manipulationResponse manipulationCacheSecurity
Vary based on a cookie
Return different objects based on the presence of a cookie.
Request manipulationCachePersonalization
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.
Request manipulationCachePerformance
Geofence / block access to content by region
Group countries to cache content by custom regions or reject requests from some regions entirely.
Response manipulationGeolocationSecurity
Cache 'near you' content for each area using lat/long grid
Bucket users into small grid squares to allow for hyper-local content caching (e.g., "stores near you", "local offers").
GeolocationCachePerformance
Set Google Analytics _ga cookie
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.
Response manipulationEdge dataSEO
Auto retry a secondary backend
If primary backend fails, retry with a different backend without caching the failure or reducing cache efficiency.
Request manipulationBackendsResilience
Comprehensive logging
Fastly offers a myriad of different variables that you can log. See and test a large collection here.
LoggingObservability
Enable features gradually
Avoid a huge inrush of traffic to origin caused by gradually applying changes that affect the cache key, like segmented caching, over hours or days.
Request manipulationCacheEdge dataDeveloper experience
Create image transform presets
Use custom, predefined classnames like large, medium, small, teaser, thumb, or article to control Fastly Image Optimizer and optionally prevent end-user access to native properties like 'width'.
Image optoResponse manipulationDeveloper experience
Use shielding to funnel origin requests though one Fastly POP
Shielding directs requests through two Fastly POPs instead of one, improving cache hit ratio and reducing traffic to your origin.
BackendsCachePerformance
Create montage poster frame images
Combine multiple source images into a single image and then optimize and serve the result.
Image optoResponse manipulationDeveloper experience
Anonymize client IPs for logging
Strip the last octet or compute a hash of client IP address for anonymization.
LoggingObservability
Log the IP version (IPv4/IPv6)
Identify which type of IP address was used by the client connecting to your Fastly service.
LoggingObservability
Send HTTP Basic Auth in request to origin
Convert a password sent by the client in the querystring into a Authorization header to your origin server.
Request manipulationEdge dataSecurity
Cache GraphQL query response
GraphQL query requests are POSTs, but normally responses to POST can't be cached. Normalize the query and convert it to a querystring on a GET request to allow Fastly to cache these responses.
Request manipulationCache
Base64 URL path segments
Unknown data in URL paths can result in invalid URLs, but base64url is designed to be URL-safe.
Request manipulation
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.
Request manipulationSecurity
Authenticate JSON Web Tokens at the edge
Decode the popular JWT format to verify user session tokens before forwarding trusted authentication data to your origin.
Request manipulationEdge dataSecurity
Use A/B testing to personalize responses
Serve different responses to separate user cohorts.
Request manipulationResponse manipulationEdge dataCachePersonalization
Redirect old URLs at the edge
Use a dictionary of URL mappings to serve your redirects at lightning speed.
Response manipulationEdge dataPerformance
Flatten the curve of major traffic spikes with a waiting room
A totally stateless solution to hold back new users for a minimum waiting period to smooth out spikes in traffic.
Request manipulationResponse manipulationEdge dataSecurity
Add time zone offset to requests
Divide the world into time bands of custom size and forward time zone data to your origin server.
Request manipulationPersonalization
Format time expressions
Format dates and times in a variety of ways.
Developer experience
Perform redirects with wildcard patterns using an edge dictionary
Match URL prefixes and make use of configurable response status and querystring preservation.
Response manipulationEdge dataDeveloper experience
Throttling per country over configurable time periods
Adjust the maximum TCP socket pacing for connections at peak times of day in busy regions.
Response manipulationEdge dataSecurity
CenturyLink-compatible token validation
Validate your CenturyLink tokens for access to video stream playlists.
Request manipulationEdge dataSecurity
Perform multiple origin requests asynchronously
Handle third-party requests as they are resolved.
FetchPerformance
Slowing down responses (tarpit)
Force a response to be delivered very slowly to reduce the rate at which an attacker can send requests.
Response manipulationSecurity
Support for Edge-Control header
Use custom edge code to implement support for the proprietary Edge-Control cache directive.
Performance
Enrich image responses with EXIF metadata
Use the `exif` Rust crate to decorate a backend response with image metadata.
Edge dataResponse manipulation
Generate a QR code
Use open source libraries to dynamically serve a QR code based on query parameters.
Use dynamic backends to follow redirects
Create a dynamic backend from the redirect response, and then get a response from the dynamic backend.
FetchResponse manipulationDeveloper experienceDynamic backend
Bot detection using ratecounter
Rate counters are normally used for detecting high volume DoS-style attacks, but you can also use them to measure lower rates, to ensure that navigation between pages is happening at human speed.
Rate limit requests
Use ratecounters and penalty boxes to stop high-volume automated attacks against your website.
Validate domain on query string
Check the query string if it contains a valid domain.
Backend health status API
Create an HTTP API for real time backend health status
ObservabilityDeveloper experience
All code on this page is provided under both the BSD and MIT open source licenses.