---
title: "Edge functions, redirects and caching on Launch"
url: "https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching"
type: "guide"
level: "intermediate"
intent: "build"
outcome: "You can route, transform, cache and debug requests on Launch with launch.json, an edge function, cache headers and the Revalidate CDN Cache API."
prerequisites:
  - "A site deployed on Contentstack Launch, or one you are about to deploy"
  - "Basic knowledge of HTTP status codes and Cache-Control headers"
  - "Familiarity with JavaScript and the Fetch API Request and Response objects"
tags:
  - "headless"
  - "api"
  - "next"
authors:
  - "Tim Benniks"
published: "2026-11-24T09:00:00.000Z"
updated: "2026-11-15T10:56:03.694Z"
---

# Edge functions, redirects and caching on Launch

- **Authors:** Tim Benniks
- **Published:** 2026-11-24T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:03.694Z
- **Level:** Intermediate
- **Intent:** Build
- **Tags:** headless, api, next
- **Chapters:** 4
- **Source:** [https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching](https://developers.contentstack.com/guides/launch-edge-functions-redirects-and-caching)

---

## Table of Contents

1. [Routing with launch.json](#routing-with-launchjson)
2. [Edge functions in practice](#edge-functions-in-practice)
3. [Caching, revalidation and cache priming](#caching-revalidation-and-cache-priming)
4. [Logs, debugging and limits](#logs-debugging-and-limits)

Every request to a Launch site passes through a few layers before your framework sees it. Most of the hard production problems live in those layers: a redirect that loops, a page that stays stale after a publish, a personalized response that leaks to the wrong visitor, or an edge function that throws CFL-0001 and only tells you so in a log you didn't know existed.

This guide walks through those layers in the order Launch runs them. It assumes you have a site on Launch already. The examples use Next.js where a framework matters, but the platform features work the same for Nuxt, Astro, Angular or a static site.

## What you'll learn

- How to write redirects and rewrites in launch.json


- When an edge function is the right tool, and how to write one for geo, auth and A/B routing


- How the Launch CDN caches responses and how to refresh it on publish


- How to read edge and server logs, forward them with Log Targets, and stay inside platform limits



## How a request moves through Launch

Launch concept: Launch puts a CDN and an edge runtime in front of your origin. You configure the first part declaratively, the second part with JavaScript, and the cache with standard HTTP headers.

flowchart LR  A[Visitor] --> B[launch.json redirects and rewrites]  B --> C["Edge function (functions/[proxy].edge.js)"]  C --> D[CDN cache]  D -->|miss| E[Origin: SSR or Cloud Functions]  D -->|hit| AA few rules follow from that order:

- A matching redirect in launch.json wins. If you define the same redirect in launch.json and in your edge function, the launch.json one runs.


- Password protection also takes precedence over the edge function.


- The edge function runs before the cache, so it can change the URL that gets cached. That is what makes it useful for A/B routing and for stripping tracking parameters.


- A request that a rewrite or an edge function forwards to the origin does not invoke the edge function a second time.



If you are coming from Vercel or Netlify, think of launch.json as the redirects and headers section of vercel.json or netlify.toml, and the edge function as a single middleware that runs on every request.

## How the chapters fit together

Each chapter covers one layer and can be read on its own.

- [Routing with launch.json](/guides/launch-edge-functions-redirects-and-caching/routing-with-launch-json) covers redirects, rewrites, path patterns, header injection and the limits of the file.


- [Edge functions in practice](/guides/launch-edge-functions-redirects-and-caching/edge-functions-in-practice) covers the handler, environment variables, geolocation headers, header-based access control and cookie-based A/B routing.


- [Caching, revalidation and cache priming](/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming) covers Cache-Control, cache tags, the Revalidate CDN Cache API, revalidating on publish and warming the cache after a deployment.


- [Logs, debugging and limits](/guides/launch-edge-functions-redirects-and-caching/logs-debugging-and-limits) covers server logs, Log Targets, the numbers you need to remember and the mistakes that show up most often.



If you only need to pick between revalidating, priming and redeploying, read [Revalidate, prime or redeploy?](/blog/revalidate-prime-or-redeploy-picking-the-right-cache-lever-on-launch) first. If you want to drive deployments from a pipeline, continue with [Deploy from CI with the Launch CLI, REST API and deploy hooks](/guides/deploy-from-ci-with-the-launch-cli-and-api).

## Key takeaways

- Put static and pattern-based redirects and rewrites in launch.json at the root of your repository.


- Reach for functions/[proxy].edge.js only when the routing decision depends on request data such as headers, cookies or location.


- Treat Cache-Control as the contract with the CDN, and refresh it with the Revalidate CDN Cache API instead of redeploying for every content change.


- Check Server Logs first when something breaks at the edge, and set up a Log Target before you need history older than 24 hours.





---

## Routing with launch.json

Most sites collect redirects over time. A migration renames /blog to /news, marketing wants /spring to point at a campaign page, and a legacy host still serves half the site. On Launch you handle all of that in one file, launch.json, and the rules run at the CDN edge closest to the visitor. No framework code runs for a redirect, which keeps them fast and keeps your app code clean.

## What you'll learn

- Where launch.json lives and how Launch picks it up


- How to write redirects with status codes, path variables and regex


- How to write rewrites that proxy to another path or host


- How to inject request and response headers


- Which limits and ordering rules to remember



## Create launch.json

Launch concept: launch.json is a configuration file in the root of your project. Launch reads it on every deployment.

Create the file next to your package.json and commit it:

```json
{
  "redirects": [],
  "rewrites": []
}
```

Nothing happens until you deploy. After a successful deployment, the deployment logs show how many redirects and rewrites Launch loaded. Check that number when a rule doesn't seem to apply. A zero usually means the file is in the wrong folder or is not valid JSON.

The same file also holds the cache priming configuration, which is covered in [chapter 3](/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming).

## Add redirects

A redirect sends the browser to a new URL. The address bar changes.

```json
{
  "redirects": [
    {
      "source": "/spring",
      "destination": "/campaigns/spring-2026",
      "statusCode": 302
    },
    {
      "source": "/blog/:slug",
      "destination": "/news/:slug",
      "statusCode": 308
    },
    {
      "source": "/docs-old",
      "destination": "https://docs.example.com/",
      "statusCode": 301,
      "response": {
        "headers": { "x-redirected-by": "launch" }
      }
    }
  ]
}
```

Pick the status code on purpose:

Status code

Meaning

Use it for

301

Permanent

Old URLs that never come back

308

Permanent, keeps the HTTP method

The default if you omit statusCode

302

Temporary

Campaigns, maintenance pages

307

Temporary, keeps the HTTP method

Temporary moves of form or API endpoints

The optional response.headers object adds headers to the redirect response itself.

## Use path variables and regex

:slug in the example above is a path variable. It captures a segment of the source and you can reuse it in the destination.

You can constrain a variable with a regular expression in parentheses. This redirect moves two blog categories into a new section and drops the category from the URL:

```json
{
  "redirects": [
    {
      "source": "/blogs/:category(product-updates|announcements)/:postId(.*)",
      "destination": "/product-updates/:postId",
      "statusCode": 301
    }
  ]
}
```

/blogs/announcements/march-release now goes to /product-updates/march-release. /blogs/engineering/march-release does not match and passes through.

Query strings are part of the match. Escape the ? as \\? in JSON, because a bare ? is a regex character. This rule turns /blogs/insights?postId=321 into /blogs/insights/321:

```json
{
  "redirects": [
    {
      "source": "/blogs/:category(.+)\\?(.*)postId=:postId(.+)",
      "destination": "/blogs/:category/:postId",
      "statusCode": 301
    }
  ]
}
```

One pattern can replace hundreds of literal rules. That matters once you approach the file size limit.

## Add rewrites

A rewrite serves a different path or host without changing the URL in the browser. Launch makes the call from the edge, so it works as a reverse proxy.

The most useful rewrite is the incremental migration. Launch serves the pages you have rebuilt, and everything else is proxied to the legacy host:

```json
{
  "rewrites": [
    {
      "source": "/:path((?!blogs|docs|about-us).+)",
      "destination": "https://legacy.example.com/:path",
      "request": {
        "headers": { "x-origin-key": "replace-with-a-shared-secret" }
      }
    }
  ]
}
```

The negative lookahead (?!blogs|docs|about-us) excludes the migrated sections. The homepage also stays on Launch, because .+ needs at least one character after the slash. The request header lets the legacy host reject traffic that doesn't come through Launch.

You can also proxy one section to a different service:

```json
{
  "rewrites": [
    {
      "source": "/assets/:category(products|storefront)/:path(.*)",
      "destination": "https://assets.example.com/:category/:path",
      "response": {
        "headers": { "x-robots-tag": "noindex" }
      }
    }
  ]
}
```

## Inject headers on every response

A rewrite to the same path is a clean way to add security headers to the whole site:

```json
{
  "rewrites": [
    {
      "source": "/:path(.*)",
      "destination": "/:path",
      "response": {
        "headers": {
          "X-Frame-Options": "DENY",
          "X-Content-Type-Options": "nosniff",
          "Referrer-Policy": "strict-origin-when-cross-origin",
          "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload"
        }
      }
    }
  ]
}
```

request.headers are added before Launch calls the destination. response.headers are added before the response goes back to the client, and they override headers with the same name from the destination.

Keep this catch-all at the end of the rewrites array. Rules are evaluated in order, so put specific rules before broad ones.

## Where people get confused

Client-side navigation skips the edge. Rules in launch.json only run when the browser makes a request to Launch. A <Link> in Next.js or a <NuxtLink> in Nuxt navigates on the client, so a rewrite for that path never runs. Use a plain <a> for links that must go through an edge rule, or handle the route in the framework.

A redirect can get cached. If your origin sends a redirect with a long s-maxage, the CDN keeps serving it after you fix the rule. Don't put long cache lifetimes on redirect responses. Chapter 3 explains how to purge a path if it already happened.

The source cannot contain a hostname. "source": "https://old.example.com/page" does not work. When several domains point at the same environment and need different rules, branch on new URL(request.url).hostname in an [edge function](/guides/launch-edge-functions-redirects-and-caching/edge-functions-in-practice).

Monorepos. Launch does not read a launch.json from an app inside a monorepo. If your Launch project builds a sub-folder, move the routing logic into an edge function or check the current Launch docs for your setup.

## Limits to remember

Limit

Value

launch.json file size

5 MB

Source URL length

512 characters

Destination URL length

512 characters

Source format

Relative path only

Hash fragments (#)

Never sent to the server, so you can't match on them

A file close to the size limit is slow to process. Long lists of one-to-one redirects usually mean the URLs follow a pattern you haven't written yet, or that the mapping belongs in an edge function that reads it from a data source.

## Key takeaways

- Put launch.json in the project root and check the redirect and rewrite counts in the deployment logs.


- Default to 308 for permanent moves and 302 for temporary ones, and set statusCode explicitly.


- Use :param(regex) patterns and escape ? as \\? to match query strings.


- Use rewrites with a negative lookahead for incremental migrations, and a final /:path(.*) rewrite for global response headers.


- Move hostname-based or data-driven routing to an edge function.





---

## Edge functions in practice

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.





---

## Caching, revalidation and cache priming

Caching on Launch is plain HTTP. Your origin sends Cache-Control, the CDN follows it, and you decide when to throw entries away. There is no framework-specific cache layer to learn, which also means framework features such as the Next.js App Router Data Cache and revalidatePath() don't apply. This chapter shows the setup that works well for content sites: long CDN lifetimes, targeted purges on publish, and a warm cache after each deployment.

## What you'll learn

- How to set Cache-Control and Cache-Tag headers in Next.js on Launch


- How to purge by path, tag or hostname with the Revalidate CDN Cache API


- How to revalidate from Automations or from a webhook when an entry is published


- How to configure cache priming in launch.json


- Which caching mistakes leak or pin content



## Set Cache-Control on the origin

Launch concept: the Launch CDN caches a response for as long as s-maxage (or max-age) allows. max-age controls the browser, s-maxage controls the CDN.

A common setup for content pages:

```text
Cache-Control: public, max-age=0, s-maxage=86400, stale-while-revalidate
```

The browser always checks with the CDN, and the CDN keeps the page for 24 hours.

In a Next.js App Router project, opt the route out of the Full Route Cache and set the header in next.config.js:

```typescript
// app/blog/[slug]/page.tsx
export const dynamic = 'force-dynamic';
```

```javascript
// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:slug*',
        headers: [
          { key: 'Cache-Control', value: 'public, max-age=0, s-maxage=86400, stale-while-revalidate' },
          { key: 'Cache-Tag', value: 'prod-blog' },
        ],
      },
    ];
  },
  generateBuildId: () => process.env.CONTENTSTACK_LAUNCH_DEPLOYMENT_UID,
};
```

generateBuildId ties the Next.js build to the Launch deployment UID. Launch documents this step for on-demand revalidation, so the CDN refreshes the right build.

Route handlers can set headers per response, which is handy for JSON endpoints:

```typescript
// app/api/products/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const products = await getProducts();
  const response = NextResponse.json(products);
  response.headers.set('Cache-Control', 'public, s-maxage=300');
  response.headers.set('Cache-Tag', 'prod-products');
  return response;
}
```

If you are on the Pages Router, Launch supports ISR there. The rest of this chapter applies either way.

## Know what the cache key is

The cache key is the URL: scheme, hostname, path and query string. Headers and cookies are not part of it. Two consequences:

- /page?utm_source=x and /page?utm_source=y are separate cache entries. Strip tracking parameters in an [edge function](/guides/launch-edge-functions-redirects-and-caching/edge-functions-in-practice) if they fragment your cache.


- A page that renders differently per cookie must send Cache-Control: no-store, or move the per-user part to a client-side call. Otherwise one visitor's response is served to everyone.



## Purge with the Revalidate CDN Cache API

Launch concept: revalidation tells the CDN to drop cached entries for an environment, across every domain attached to it. The next request goes to the origin.

```bash
curl -X POST \
  "https://launch-api.contentstack.com/projects/$PROJECT_UID/environments/$ENVIRONMENT_UID/revalidate-cdn-cache" \
  -H "Authorization: Bearer $LAUNCH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "cachePath": { "path": "/blog", "isPrefix": true } }'
```

The body takes exactly one of three inputs:

Input

Example

Purges

cachePath

{ "path": "/blog/my-post", "isPrefix": false }

One path, or everything under it with isPrefix: true

cacheTags

["prod-blog"]

Every response that carried one of these tags

hostnames

["www.example.com"]

Everything for those domains

Use the base URL for your region, for example https://eu-launch-api.contentstack.com in AWS EU. With an authtoken instead of OAuth, send authtoken and organization_uid headers. A successful call returns "The CDN cache revalidation task has been initiated."

{ "path": "/", "isPrefix": true } clears the whole site without a deployment. You can also purge by path, tag or domain from Settings > Environments > Cache in Launch.

Tags are the efficient option. One request with cacheTags can clear hundreds of URLs. Put an environment prefix in every tag, such as prod-blog and staging-blog, in both the header and the purge request. That way a purge triggered for staging can never touch production pages that share a tag name.

## Revalidate when content is published

You have two ways to call the API on publish.

Automations. The Launch connector in Automations has a Revalidate CDN Cache action. Trigger it on entry publish, map the entry URL to the path, and you are done without writing code. The [Automate guides](/guides/automate-recipe-for-content-type-propagation) show how to build a trigger and action flow.

A webhook handler in your app. If you prefer code, point a Contentstack webhook at a route in your own site and call the API from there:

```typescript
// app/api/revalidate/route.ts
export async function POST(request: Request) {
  if (request.headers.get('x-webhook-secret') !== process.env.WEBHOOK_SECRET) {
    return new Response('Unauthorized', { status: 401 });
  }

  const payload = await request.json();
  const contentType = payload?.data?.content_type?.uid;
  const url = payload?.data?.entry?.url;

  const purge = (body: object) =>
    fetch(
      `https://launch-api.contentstack.com/projects/${process.env.LAUNCH_PROJECT_UID}/environments/${process.env.LAUNCH_ENVIRONMENT_UID}/revalidate-cdn-cache`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.LAUNCH_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
      }
    );

  const jobs = [];
  if (url) jobs.push(purge({ cachePath: { path: url, isPrefix: false } }));
  if (contentType === 'blog_post') jobs.push(purge({ cacheTags: ['prod-blog'] }));

  await Promise.all(jobs);
  return Response.json({ revalidated: jobs.length });
}
```

Add x-webhook-secret as a custom header on the webhook in your stack settings, and send Cache-Control: no-store from this route if your framework doesn't already. Check the webhook payload of your stack before you rely on data.entry.url. Content types without a url field need a mapping from entry to path.

sequenceDiagram  participant Editor  participant CMS as Contentstack  participant App as /api/revalidate on Launch  participant API as Launch API  participant CDN as Launch CDN  Editor->>CMS: Publish entry  CMS->>App: Webhook (entry, content type)  App->>API: POST revalidate-cdn-cache (path or tags)  API->>CDN: Purge matching entries  Note over CDN: Next request is a miss and goes to the origin## Stay inside the quota

Revalidation has a daily quota per organization, and calls past it return 429. Check it from your pipeline or a dashboard:

```bash
curl "https://launch-api.contentstack.com/usage-analytics/revalidate-cdn-cache" \
  -H "Authorization: Bearer $LAUNCH_TOKEN"
```

The response has currentCacheRevalidations, maxCacheRevalidations and a usageReset timestamp. Tags and prefixes keep the count low. A failing automation that sends the same purge on a loop is the usual way teams run out.

## Warm the cache with cache priming

Every deployment purges the CDN, so the first visitor to each page after a release waits for the origin. Cache priming requests a list of paths as part of the deployment so they are cached before real traffic arrives.

Add the paths to launch.json:

```json
{
  "cache": {
    "cachePriming": {
      "urls": ["/", "/pricing", "/blog", "/docs"]
    }
  }
}
```

Then turn on Enable Cache Priming in Settings > Environments > Cache. The setting applies from the next deployment.

Rules for the list:

- Use relative paths only. Full URLs, wildcards and regex are not supported, so generate the list at build time if it comes from content.


- Only list routes that send a cacheable Cache-Control. A no-store route is requested and logged, but never cached.


- Priming requests use the user agent Contentstack-Launch/CachePrimingAgent/1.0. Allow it in your WAF, and filter on it in analytics. Don't use it for authentication.


- A route that fails to prime doesn't fail the deployment.



## Where people get confused

Long lifetimes on the wrong responses. A one-year s-maxage on HTML is fine when you purge on publish. On a redirect or an error-prone route it pins a mistake at the edge. Purge the path with cachePath to recover.

Counting on stale-while-revalidate. Treat it as a bonus. Size s-maxage and your purge strategy so that pages are fresh without it, and check cf-cache-status and age response headers when you test.

Redeploying to publish content. It works, because a deployment purges the cache, but every publish becomes a full build. Use revalidation for content and deployments for code. The trade-offs are in [Revalidate, prime or redeploy?](/blog/revalidate-prime-or-redeploy-picking-the-right-cache-lever-on-launch).

## Key takeaways

- Send public, max-age=0, s-maxage=<seconds> for content pages and no-store for anything that depends on cookies.


- Add Cache-Tag headers with an environment prefix, such as prod-blog.


- Purge with POST /projects/{project_uid}/environments/{environment_uid}/revalidate-cdn-cache and one of cachePath, cacheTags or hostnames.


- Trigger revalidation on publish with the Automations Launch connector or a small webhook route.


- List your most visited routes under cache.cachePriming.urls and enable cache priming in the environment settings.


- Watch GET /usage-analytics/revalidate-cdn-cache so you don't hit the daily quota.





---

## Logs, debugging and limits

Edge problems are hard to see from the browser. A 500 from the edge, a page that won't update, or a redirect that fires for the wrong visitors all look the same in a network tab. Launch gives you three places to look: deployment logs for build and bundling errors, server logs for runtime output, and response headers for cache behavior. This chapter shows how to use each one, how to keep logs longer than a day, and which limits cause most failures.

## What you'll learn

- How to read edge and server logs in the UI, the CLI and the API


- How to forward logs to your own platform with Log Targets


- How to diagnose CFL-0001 and failed edge deployments


- Which platform limits apply to edge functions, routing and environment variables


- The mistakes that show up most often in production



## Read server logs

Launch concept: server logs hold runtime output from your SSR app, Cloud Functions and edge functions for the latest deployment. Every console.log, console.error and unhandled exception from functions/[proxy].edge.js lands there.

In Launch, open the environment and go to the server logs. Retention is 24 hours, with up to 5,000 recent entries viewable.

From a terminal, the CLI fetches the same logs. The Launch commands are not part of the default CLI install; they come from the @contentstack/cli-launch plugin, so install it once:

```bash
csdx plugins:install @contentstack/cli-launch

# Server logs (the default type)
csdx launch:logs --environment production --type s

# Deployment (build) logs for a specific deployment
csdx launch:logs --environment production --deployment <deployment-uid> --type d
```

Run these from a folder that has the .cs-launch.json file the CLI created, or pass --org and --project.

For scripts, the Launch API returns server logs per deployment and can filter to edge output only:

```bash
curl -G "https://launch-api.contentstack.com/projects/$PROJECT_UID/environments/$ENVIRONMENT_UID/deployments/$DEPLOYMENT_UID/logs/server-logs" \
  -H "Authorization: Bearer $LAUNCH_TOKEN" \
  --data-urlencode "source=edge-logs" \
  --data-urlencode "search=TypeError" \
  --data-urlencode "limit=200"
```

source is edge-logs for edge functions or origin for SSR and Cloud Functions. search matches text in the log message.

Log with structure. A JSON line with the path and the decision you made is easier to search than free text:

```javascript
export default async function handler(request, context) {
  const url = new URL(request.url);
  try {
    const response = await fetch(request);
    if (response.status >= 500) {
      console.error(JSON.stringify({ event: 'origin_error', path: url.pathname, status: response.status }));
    }
    return response;
  } catch (error) {
    console.error(JSON.stringify({ event: 'edge_exception', path: url.pathname, message: String(error) }));
    return new Response('Service unavailable', { status: 503, headers: { 'cache-control': 'no-store' } });
  }
}
```

The try/catch turns an unhandled exception into a controlled 503 with a log line you can find.

## Forward logs with Log Targets

Server logs are short-lived on purpose. For history, alerting and correlation with the rest of your stack, set up a Log Target. It forwards logs over OTLP (OpenTelemetry Protocol) to any endpoint that accepts it, either directly to your log provider or through an OpenTelemetry Collector.

Create one in Launch under Settings > Log Targets:

- Give the target a name and pick the data types: Server Logs (SSR, Cloud Functions and edge functions) and/or Traffic Logs (request and response metadata from the CDN edge).


- Choose All Projects & Environments or a Custom set of projects and environments.


- Set the delivery protocol (gRPC or HTTP), the endpoint URL, any authentication headers your provider needs, and the payload format. JSON is only available over HTTP.


- Run Test Connection. A target saved without a successful test stays disabled until you verify it.



Each combination of environment and data type can be covered by only one Log Target. One target can forward server logs for production while another forwards traffic logs for the same environment.

Logs are forwarded exactly as your code wrote them. Launch does not mask anything, so keep tokens and personal data out of console.log.

## Debug common errors

Internal server error CFL-0001. Your edge function threw an unhandled exception. Open server logs filtered to edge output. Typical causes are calling request.json() on a request without a body, reading a missing context.env value, or mutating a Request or Response instead of creating a new one.

The deployment fails at the edge function step. The deployment logs name the reason. The usual ones:

- The minified bundle of your code and its imports is larger than 1 MiB.


- A dependency uses Node.js APIs that aren't in the WinterCG minimum set.


- Bundling failed because of a syntax error or a missing dependency in package.json.


- An environment variable contains quotes, extra spaces or escaped newlines, for example key="1234" instead of key=1234.



New code only works some of the time. Edge functions roll out to all points of presence within about 60 seconds. During that window, and for logs, some requests still hit the previous deployment. Wait a minute before you conclude a fix didn't work.

A page is stale or a fix doesn't show. Look at the response headers. cf-cache-status: HIT with a large age means you are seeing a cached copy. Revalidate the path as described in [chapter 3](/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming), then check your Cache-Control.

A rule in launch.json doesn't run. Check the redirect and rewrite counts in the deployment logs, then check whether the link is a client-side navigation that never reaches the edge.

## Limits to remember

Area

Limit

Edge function memory

128 MB per instance

Edge function bundle

1 MiB (1,024 KiB) minified

Edge function startup

400 ms for the global scope

Edge function duration

No limit while the client stays connected

Edge function environment variables

Up to 64, each up to 5 KB

Environment variables per environment

128, with 14 KB in total

Environment variables with Cloud Functions

4 KB in total

launch.json file size

5 MB

Redirect or rewrite source and destination

512 characters each

Server log retention

24 hours, up to 5,000 entries viewable

Launch API rate limit

10 requests per second per organization

The 400 ms startup limit is about code outside the handler. Don't parse a large JSON file or build a big lookup table at the top level of the module.

Running edge functions locally with the CLI is not supported. csdx launch:functions serves Cloud Functions only. Keep the handler logic in small, pure functions you can unit test with Node's built-in Request and Response, and deploy to a preview environment for the rest.

## Where people get confused

Logging secrets. A console.log(request.headers) prints cookies and auth headers into your logs and into every Log Target. Log the fields you need.

Caching error responses from the edge. A 403 or 503 returned by your edge function without cache-control: no-store can be cached like any other response.

Blocking or trusting cache priming. Priming requests come from platform IP addresses with the Contentstack-Launch/CachePrimingAgent/1.0 user agent. A WAF or IP allowlist in front of your site can block them, so priming silently does nothing. Allow them, but don't treat that user agent as proof of anything, because any client can send it.

## Key takeaways

- Check deployment logs for bundling errors and server logs for runtime errors, filtered to edge output.


- Use csdx launch:logs --type s or the server-logs API with source=edge-logs in scripts.


- Wrap edge logic in try/catch and log JSON lines so CFL-0001 becomes a searchable error.


- Set up a Log Target over OTLP before you need history older than 24 hours.


- Keep the edge bundle under 1 MiB, global scope work under 400 ms, and environment variables free of quotes and escaped newlines.





---

## 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 my launch.json and functions folder and explain, for a request to /blog/old-post, which redirect, rewrite or edge function runs first and which cache headers the response ends up with.

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




---

## Frequently asked questions

### In what order does Launch process a request?

Redirects and rewrites from launch.json run first, then your edge function, then the CDN cache, and finally your origin (SSR or Cloud Functions).

### Do I need an edge function for redirects?

No. Static and pattern-based redirects belong in launch.json. Use an edge function when the decision depends on headers, cookies, geolocation or the hostname.

### Does Launch support Next.js revalidatePath and revalidateTag?

Not with the App Router Data Cache. On Launch you control caching with Cache-Control headers and refresh the CDN with the Revalidate CDN Cache API, Automations or a redeploy.

### Where do I see console.log output from an edge function?

In the Server Logs of the environment in Launch, with the CLI using csdx launch:logs, or in your own tooling through a Log Target.

