---
title: "Edge functions in practice"
url: "https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching/edge-functions-in-practice"
type: "guide_chapter"
level: "intermediate"
intent: "build"
outcome: "You have a functions/[proxy].edge.js that routes by country, hostname and A/B cookie, protects a path with a header token, and keeps responses cacheable."
prerequisites:
  - "A Launch project you can deploy to"
  - "Working knowledge of the Fetch API Request, Response and Headers objects"
  - "Read the routing with launch.json chapter, or know when declarative rules are enough"
next:
  - "https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming"
tags:
  - "headless"
  - "api"
  - "security"
  - "next"
authors:
  - "Tim Benniks"
published: "2026-11-15T10:15:07.734Z"
updated: "2026-11-15T10:55:19.725Z"
---

# Edge functions in practice

- **Authors:** Tim Benniks
- **Published:** 2026-11-15T10:15:07.734Z
- **Updated:** 2026-11-15T10:55:19.725Z
- **Level:** Intermediate
- **Intent:** Build
- **Tags:** headless, api, security, next

---

launch.json handles rules you can write down ahead of time. Some routing decisions depend on the request itself: the visitor's country, a cookie, a header, or which of your domains they hit. That is what Launch edge functions are for. The function runs at the edge before the CDN cache, so it can change the request, return a response directly, or forward to the origin.

## What you'll learn

- The handler signature, the context object and the runtime rules


- How to route visitors by geolocation headers


- How to protect a path with a header token stored in an environment variable


- How to route by hostname when several domains share an environment


- How to run a cookie-based A/B test without breaking the CDN cache



## Start from the handler

Launch concept: an edge function is one file, functions/[proxy].edge.js, in the root of your project. It exports a default handler that receives a standard Request and returns a standard Response.

```javascript
// functions/[proxy].edge.js
export default function handler(request, context) {
  return fetch(request);
}
```

fetch(request) forwards the request to your Launch origin. That one line is the "do nothing" edge function, and every example below falls back to it.

The context object gives you two things:

- context.env holds the environment variables of the Launch environment.


- context.waitUntil(promise) keeps work running after you return the response, for example a call to an analytics endpoint.



The runtime is WinterCG compliant, not Node.js. You get fetch, URL, Headers, Request, Response, Web Streams, TextEncoder and crypto.subtle. Importing a package that relies on Node.js built-ins fails the deployment, so check dependencies before you add them.

Your edge function runs on every request that launch.json didn't already redirect, including images and JavaScript chunks. Return early for paths you don't care about:

```javascript
export default function handler(request, context) {
  const url = new URL(request.url);

  if (url.pathname.startsWith('/_next/') || url.pathname.startsWith('/static/')) {
    return fetch(request);
  }

  // edge logic for pages goes here
  return fetch(request);
}
```

## Route by country

Launch adds geolocation headers to every incoming request:

Header

Example

visitor-ip-country

US (two-letter country code)

visitor-ip-region

Oregon

visitor-ip-city

The Dalles

This handler sends visitors from Germany, Austria and Switzerland on the homepage to the German site, unless they already chose a locale:

```javascript
const DACH = ['DE', 'AT', 'CH'];

export default function handler(request, context) {
  const url = new URL(request.url);
  const country = request.headers.get('visitor-ip-country') || '';
  const cookies = request.headers.get('cookie') || '';
  const choseLocale = cookies.includes('locale=');

  if (url.pathname === '/' && DACH.includes(country) && !choseLocale) {
    url.pathname = '/de';
    return Response.redirect(url.toString(), 302);
  }

  return fetch(request);
}
```

Two things to watch. VPNs, proxies and new IP ranges can give an empty or wrong value, so always have a default. And use a 302, because the right answer depends on who is asking.

## Protect a path with a header token

Launch has built-in password protection for whole environments. For a single path, such as an internal preview API, check a header against a secret in an environment variable:

```javascript
async function sha256(value) {
  const bytes = new TextEncoder().encode(value);
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

export default async function handler(request, context) {
  const url = new URL(request.url);

  if (url.pathname.startsWith('/api/internal/')) {
    const token = request.headers.get('x-internal-token') || '';
    const [given, expected] = await Promise.all([sha256(token), sha256(context.env.INTERNAL_TOKEN || '')]);

    if (!context.env.INTERNAL_TOKEN || given !== expected) {
      return new Response('Forbidden', {
        status: 403,
        headers: { 'cache-control': 'no-store' },
      });
    }
  }

  return fetch(request);
}
```

Hashing both values before comparing avoids leaking the token length through timing. The no-store header keeps the CDN from caching the 403. Add INTERNAL_TOKEN in the environment settings and redeploy, because environment variables are applied on deployment.

The client IP is in the x-forwarded-for header if you need an allowlist instead.

## Route by hostname

Sources in launch.json cannot include a hostname. When shop.example.com and www.example.com point at the same environment, branch in the edge function:

```javascript
export default function handler(request, context) {
  const url = new URL(request.url);

  if (url.hostname === 'shop.example.com' && !url.pathname.startsWith('/shop')) {
    url.pathname = `/shop${url.pathname}`;
    return fetch(new Request(url.toString(), request));
  }

  return fetch(request);
}
```

The visitor still sees shop.example.com/products, and your app serves /shop/products. Because the hostname is part of the CDN cache key, both domains get their own cache entries.

## Run an A/B test that stays cacheable

Where people get confused: the Launch CDN caches by URL. It does not vary the cache on cookies. If your origin renders variant A or B based on a cookie and sends a cacheable response, the first visitor decides what everyone else sees.

The fix is to turn the cookie into a URL before the cache. The edge function picks a bucket, rewrites the request to a variant path, and sets a cookie so the visitor stays in that bucket:

```javascript
const EXPERIMENT = 'pricing-2026';

export default async function handler(request, context) {
  const url = new URL(request.url);

  if (url.pathname !== '/pricing') {
    return fetch(request);
  }

  const cookies = request.headers.get('cookie') || '';
  const match = cookies.match(new RegExp(`${EXPERIMENT}=(a|b)`));
  const bucket = match ? match[1] : Math.random() < 0.5 ? 'a' : 'b';

  url.pathname = `/pricing/${bucket}`;
  const originResponse = await fetch(new Request(url.toString(), request));

  const response = new Response(originResponse.body, originResponse);
  if (!match) {
    response.headers.append(
      'set-cookie',
      `${EXPERIMENT}=${bucket}; Path=/; Max-Age=2592000; SameSite=Lax; Secure`
    );
  }
  return response;
}
```

Your app renders /pricing/a and /pricing/b as normal cacheable pages. The CDN stores one entry per variant, and the edge function decides which one each visitor gets. The Set-Cookie header is added to a new Response built from the origin response. Don't mutate the original Request or Response objects; create new ones from them, as the examples do.

If you also run Contentstack Personalize, read [Personalize with SSR at the edge](/guides/personalize-with-ssr-at-the-edge) before you build your own bucketing. The same cache rule applies there.

## Remember that edge fetches are cached

Calls from the edge function to other domains also pass through the Launch cache layer, and they respect the Cache-Control headers the other server returns. A third-party API without cache headers can end up cached longer than you expect. A redeploy purges the cache for your origin, not for external domains you fetched from the edge. Make sure the APIs you call send explicit Cache-Control headers.

## Key takeaways

- Put your edge logic in functions/[proxy].edge.js and forward everything else with return fetch(request).


- Return early for static asset paths, because the function runs on every request.


- Read location from visitor-ip-country, visitor-ip-region and visitor-ip-city, and always handle an empty value.


- Keep secrets in context.env and send cache-control: no-store on auth failures.


- Rewrite cookie-based variants to distinct URLs so the CDN caches each variant separately.


- Build new Request and Response objects instead of mutating the ones you receive.





---

## Do this with AI

Install the launch-platform skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills). Then ask your agent:

> Read functions/[proxy].edge.js and list every code path that returns a response without a Cache-Control header or reads a cookie the cache does not vary on, then draft fixes for me to review.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### Can I write a Launch edge function in TypeScript?

Not directly. The edge function must be JavaScript. If you author in TypeScript, compile it to functions/[proxy].edge.js in your build step.

### Can I use Node.js modules in an edge function?

No. The runtime is WinterCG compliant, so you get web APIs such as fetch, URL, Headers and crypto.subtle, but not fs, path or other Node.js built-ins.

### How do I read environment variables in an edge function?

Through the context object, for example context.env.API_TOKEN. Add the variables in the environment settings in Launch.

### Can I run Launch edge functions locally with the CLI?

No. csdx launch:functions serves Cloud Functions only, so test edge logic with small deployments or unit tests around the handler.



---

## Chapter Navigation

**← Previous:** [Routing with launch.json](https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching/routing-with-launch-json)

**Next →:** [Caching, revalidation and cache priming](https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming)
