Allow conditional GET requests to origin with 304 response, even if 'outer' request from browser is not conditional.
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.
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.
Add GeoIP 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 like "3 minutes ago" at the Edge instead of in JavaScript 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.
Prioritize human traffic over search crawlers by serving stale content to crawlers.
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.
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.
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.
Fastly imposes per-request resource limits on customers' use of our edge network. If you set too many headers, this happens.
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.
If origin responds with 500 internal server error, modify status to 503 and serve a 'safe' error message.
Browsers send OPTIONS requests before performing cross-origin POSTs. You can answer these requests directly from the edge.
Store username/password list in an edge dictionary, authorize user at the edge, reject requests that don't have correct credentials.
Include full text of robots.txt in VCL, serve as a synthetic response to avoid robots.txt requests hitting your origin.
Deal with all potential scenarios for using stale content to satisfy requests when origin is unhealthy or misbehaving.
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.
Try backends in turn until one is healthy (also known as an 'active-standby' strategy)
Map requests to backends based on user ID (a.k.a., "sticky sessions"). Defaults to IP address but you can customize.
Emit logging data to your chosen log endpoint from any VCL stage, not just vcl_log.
Range headers sent from client are stripped by Fastly so we can cache the full object at the edge.
Serve binary objects, such as images, directly from edge configuration by encoding them using Base64 encoding.
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.
Make URLs expire after a configurable period.
Use Fastly Image Optimizer to transform and serve images at the edge, closer to your users.
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.
Go from an F to an A grade on securityheaders.io by adding security policy headers to your responses at the edge.
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.
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.
Compress HTML, SVG, and other compressible formats at the edge and store and serve both compressed and uncompressed versions
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.
Use addition, subtraction, multiplication, division, and modulus operators when assigning numeric values to headers or variables.
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.
Use our re.group variable to capture regex pattern groups.
Use a public GCS bucket as a backend for your Fastly service.
Block a list of IP addresses from accessing your service and include an expiry time.
Block a list of IP address ranges from accessing your service.
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 (regsub) to map paths, strip extraneous slashes, and more.
Use AWS authenticated requests (signature version 2) to protect communication between your Fastly service and AWS.
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.
Represent non-ASCII characters in VCL using unicode escapes.
Access the body of a POST request in Base64-encoded form.
Logical expressions involving the left side of an assignment as an operand.
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.
Cached a large number of objects for too long and want to update and shorten their TTLs.
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.
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.
Redirect any requests that come in on insecure HTTP, to the equivalent TLS endpoint.
Protect clients from redirects by chasing them internally at the edge, and then return the eventual non-redirect response.
If a backend returns a 429, cache it for the requesting IP but continue to allow other clients to use origin.
Return different objects based on the presence of a cookie.
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.
Fastly offers a myriad of different variables that you can log. See and test a large collection here.
The web application firewall catches a variety of different types of malicious requests including cross-site scripting (XSS), SQL injection, remote and local file inclusion (RFI, LFI), remote command execution (RCE) and session fixation.
The web application firewall has thousands of rules built in, but you can augment these with your own.
By default, the web application firewall has a single, standard response for blocked requests, but you can vary this to confuse attackers.
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.
The web application firewall runs only on traffic to your origin, but you can further refine when it should be invoked.
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'.
Shielding directs requests through two Fastly datacenters instead of one, improving cache hit ratio and reducing traffic to your origin.
Combine multiple source images into a single image and then optimize and serve the result.
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 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.
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.
A totally stateless solution to hold back new users for a minimum waiting period to smooth out spikes in traffic.
Send required resources along with page responses, before the resources are requested by the browser.
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.
Use AWS compat mode to make authenticated requests to your GCS bucket.
Validate your CenturyLink tokens for access to video stream playlists.
All code on this page is provided under both the BSD and MIT open source licenses.