Code examples in JavaScript | Fastly Documentation (original) (raw)

  1. Home
  2. Solutions
  3. Code examples

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.

Purge everything under a URL path prefix

Use surrogate keys to link all objects under each path prefix, allowing wildcard purging of all URLs that share a common prefix.

Verify if a web crawler accessing your server really is Googlebot

An implementation of Google's recommended mechanism for verifying googlebot

Add a new field to a JSON response

Decorate API responses in JSON format with new fields.

Populate template placeholders in streaming responses

Use a transform stream to search the body of a response and replace simple template placeholders with content generated at the edge, without buffering.

Use a templating library at the edge

Generate an invoice at the edge by rendering an HTML template with the full power of a popular template engine.

Geo-IP API at the edge

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.

Tag requests with geolocation data

Add geolocation 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).

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.

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).

Convert timestamps to relative times like '2 hours ago'

Generate relative time datelines at the Edge instead of in the browser or at origin. Better caching, faster rendering, fewer reflows.

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 a 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.

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.

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.

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 a dictionary, authorize user at the edge, reject requests that don't have correct credentials.

Serve robots.txt from the edge

Serve full text of robots.txt as a synthetic response to avoid requests hitting your origin.

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").

Log the data you need for actionable insights

Emit logging data to your chosen log endpoint from any VCL stage, not just vcl_log.

Serve small binary assets direct from edge

Serve binary objects, such as images, directly from edge configuration.

Create self-destructing URLs for time-limited access

Make URLs expire after a configurable period.

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.

Rewrite URL path

Receive a request for one path but request a different path from origin, without a redirect.

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.

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.

Remove trailing slashes to normalize URLs

Treat URLs with and without suffixed slashes as equivalent, or redirect URLs with slashes to the version without.

Caching responses to POST requests

By default, Fastly does not cache responses to POST requests. But you can enable this if you wish.

Ban bad IPs for a fixed period

Block a list of IP addresses from accessing your service and include an expiry time.

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.

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.

Log request data to Google BigQuery

Build raw JSON strings matching your BigQuery table schema to send log data to BigQuery.

POST to GET rewrite using a Base64-encoded querystring

To allow caching of POST requests, consider rewriting them as GET requests at the edge.

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.

Smoke test a new origin

Send a copy of your traffic to a test origin before returning a response from production.

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.

Decompress and read gzipped responses

When you need to work on API and text responses from backends that support gzip.

Prohibit browser caching

Ensure resources are not cached on the front end, while allowing caching within Fastly.

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.

Clean backend responses

Remove headers added by backends that you don't want to emit to the browser, like amz- or goog- headers.

Follow redirects at the edge

Protect clients from redirects by chasing them internally at the edge, and then return the eventual non-redirect response.

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.

Geofence / block access to content by region

Group countries to cache content by custom regions or reject requests from some regions entirely.

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").

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.

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.

Log the IP version (IPv4/IPv6)

Identify which type of IP address was used by the client connecting to your Fastly service.

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.

Cache POST/GraphQL query responses

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.

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.

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.

Use A/B testing to personalize responses

Serve different responses to separate user cohorts.

Redirect old URLs at the edge

Use a dictionary of URL mappings to serve your redirects at lightning speed.

Add time zone offset to requests

Divide the world into time bands of custom size and forward time zone data to your origin server.

Format time expressions

Format dates and times in a variety of ways.

Perform redirects with wildcard patterns using a dictionary

Match URL prefixes and make use of configurable response status and querystring preservation.

Throttling per country over configurable time periods

Adjust the maximum TCP socket pacing for connections at peak times of day in busy regions.

CenturyLink-compatible token validation

Validate your CenturyLink tokens for access to video stream playlists.

Asynchronous origin requests with an ordered response

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).

Perform multiple origin requests asynchronously

Handle third-party requests as they are resolved.

Slowing down responses (tarpit)

Force a response to be delivered very slowly to reduce the rate at which an attacker can send requests.

Enrich image responses with EXIF metadata

Use the `exif` Rust crate to decorate a backend response with image metadata.

Use dynamic backends to follow redirects

Create a dynamic backend from the redirect response, and then get a response from the dynamic backend.

Backend health status API

Create an HTTP API for real time backend health status

Protect PNGs for Acropalypse

Remove extraneous data from PNG files created using screenshotting tools

Transform a response while streaming it

Streaming transformations avoid buffering a response, reducing latency and memory consumption

Set a timeout on a Request

Configure a timeout for a specific origin request, rather than relying on the configuration settings for that origin

Conduct security chaos experiments in requests

Strips cookies and forces cross-site origin headers in requests to verify security controls and logging are working as expected.

Block bad user-agents

Check for known bad bots and crawlers and deny traffic.

Rewrite url based on the subdomain

Check for a subdomain and rewrite the URL path.

Deny access to certain file types

Check for specific URL extensions and deny access with a 403.

Block all traffic from certain countries

Check for a country code on an incoming request, and if it's present, deny access with a 403.

Use surrogate key purges for purge-all and single URL purge

Surrogate key purges are fast and flexible and can be used in place of single URL purge and purge-all.

Use regionally distributed origin servers

If you have multiple hosting locations, Fastly can route traffic to the closest one.

Pass all requests

Disable edge caching and skip the Fastly readthrough cache for every request, ensuring nothing is cached at the edge.

Read environment variables

Read values from Fastly-defined env vars in Compute programs.

Register a dynamic backend

Backends can be defined at runtime in compute applications to make requests to any host on the internet.

Calculate the distance between two points on Earth

Calculate the physical geo distance in kilometers between places such as the end user's location and the Fastly POP they connected to.

All code on this page is provided under both the BSD and MIT open source licenses.