qko@coffee:~$

$ cd /articles

Pull request previews with S3 and CloudFront

How to give every PR of a single-page application its own preview URL, with one S3 bucket, one CloudFront distribution and a cookie. No environment to spin up, no limit on parallel previews.

3 min read #cloudfront #aws

A shared environment shows one version of the frontend at a time. To try several changes in parallel, before they are merged, each pull request needs its own copy of the frontend.

That copy does not have to be a full environment. A SPA is only static files, so a copy is just another folder. The infrastructure stays the same for every PR, only the files change.

No cost or moving parts are added per PR, and there is no limit on the number of previews.

How it works

Each PR is uploaded to its own folder in a single S3 bucket. A single CloudFront distribution serves all of them. A cookie tells CloudFront which folder to serve, and a lifecycle rule removes the old ones. The pipeline builds the pull request and copies the output under its prefix:

aws s3 rm  "s3://previews/pr-${PR_ID}/" --recursive
aws s3 cp build/ "s3://previews/pr-${PR_ID}/" --recursive

Then it posts the link: https://preview.example.com/?preview=pr-${PR_ID}.

Serving each preview from a path such as /pr-123/ does not work for a single-page application. Bundlers emit absolute asset URLs (/assets/index-abc.js) and the router expects to own /. A sub-path means building with a different base path, so a different artifact than the one going to production. The preview is selected by a cookie instead, and the URL stays at the root.

The first request sets it, and every following request is rewritten from /assets/index-abc.js to /pr-123/assets/index-abc.js and the application never knows it lives in a folder.

Infrastructure side

The routing is a CloudFront Function on viewer-request.

A minimal version, to adapt to the application:

function handler(event) {
    var request = event.request;
    var preview = request.querystring.preview;

    // ?preview=pr-123: store it in a cookie, then reload without the query string
    if (preview) {
        return {
            statusCode: 302,
            headers: { location: { value: request.uri } },
            cookies: { "__Host-preview": { value: preview.value, attributes: "Path=/; Secure" } },
        };
    }

    // Serve from the preview folder, index.html for anything that is not a file
    var cookie = request.cookies["__Host-preview"];
    if (!cookie || !/^pr-\d+$/.test(cookie.value)) {
        return { statusCode: 404, statusDescription: "Not Found" };
    }
    var path = request.uri.includes(".") ? request.uri : "/index.html";
    request.uri = "/" + cookie.value + path;
    return request;
}

The cookie is checked against ^pr-\d+$ before use, since it ends up in an S3 key. The __Host- prefix makes the browser refuse the cookie unless it is Secure, has Path=/ and no Domain, so it cannot be set from or leak to another subdomain.

Old previews are removed by a lifecycle rule on the bucket:

resource "aws_s3_bucket_lifecycle_configuration" "previews" {
  bucket = aws_s3_bucket.previews.id

  rule {
    id     = "expire-previews"
    status = "Enabled"

    filter {}

    expiration {
      days = 14
    }
  }
}

Expiration counts from the object’s creation date. Each push re-uploads every file with cp, which resets the clock, so an active pull request keeps its preview.

One left untouched for two weeks loses it, and the next push brings it back. sync would skip unchanged files, which would then expire in the middle of an active pull request.

The previews talk to the staging backend. With runtime configuration, the preview distribution serves its own /runtime-config.js, and a pull request is built like any other artifact.

End result: one bucket, one distribution, one function and one rule. Nothing is created per pull request, a preview costs a few megabytes in S3, and the reviewer gets a link.