mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
Studio's TanStack build serves every client JS/CSS chunk from Vercel at
`/dashboard/_vercel/immutable/...`, and each of those requests also goes
through the www zone's routing (supabase.com/dashboard is proxied by
www). The Next build served the same files from the R2 asset CDN. This
moves the TanStack build's client assets back to the asset CDN on
production builds, using native Vite / TanStack Start hooks rather than
an `assetPrefix`-style rewrite.
**Added:**
- `apps/studio/asset-cdn.ts`: one gate shared with `next.config.ts`
(production or `FORCE_ASSET_CDN=1`, `FORCE_ASSET_CDN=-1` disables,
staging CDN when `NEXT_PUBLIC_ENVIRONMENT=staging`) plus URL helpers.
Only files under `_vercel/immutable/` are rewritten, and web workers
never are
- `upload-static-assets.sh tanstack`: syncs
`.vercel/output/static/_vercel/immutable` to
`<SITE_NAME>/tanstack/_vercel/immutable` on R2 with `max-age=31536000,
immutable`. Uses `--size-only` (names are content hashes, so only new
files upload) and excludes source maps. Local files are kept
- The upload script now fails with a clear message when the asset CDN is
enabled but `ASSET_CDN_S3_ENDPOINT` or the AWS keys are missing, instead
of the AWS CLI failing on an empty `--endpoint-url`
- Unit tests for the gate and URL helpers
**Changed:**
- `server.ts` uses `createStartHandler({ transformAssets })` so the
shell's scripts, modulepreloads and stylesheets point at the CDN with
`crossorigin="anonymous"` (module scripts need CORS; it also keeps full
error details in Sentry)
- `vite.config.ts` sets `experimental.renderBuiltUrl` (client only) so
URLs inside the bundle follow: the preload helper's dependency map, and
fonts/images referenced from CSS. The CDN base is computed once from the
process env (the same env the upload script sees) and inlined into both
server and client so they can't disagree
- `build:tanstack` runs the upload after `vite build` unless
`SKIP_ASSET_UPLOAD=1`, the same as `build:next`. The Docker image's
TanStack build sets `SKIP_ASSET_UPLOAD=1` (images serve their own
assets, and the pruned context has no upload script)
**Unchanged on purpose:**
- Vite `base` and the router basepath stay `/dashboard`; documents,
`/_serverFn` and `/api` stay on Vercel
- Web workers stay same-origin (`worker-src 'self' blob: data:`, and
workers must be same-origin anyway), so `immutableStaticFiles` stays on
- With the CDN off (previews, self-hosted), the build output is
identical to master apart from release hashes
The CDN folder is shared and content-addressed rather than per-commit,
so unchanged chunks dedupe across deploys and older tabs keep finding
their lazy chunks whichever deployment serves the next document.
**Rollout:** production has `FORCE_ASSET_CDN=-1` for now, so merging
this doesn't change prod. Staging picks it up on merge and gets tested
first.
## To test
### On the preview (tests the upload, not the page)
The staging preview for this branch builds with `FORCE_ASSET_CDN=1`, so
it exercises the real build-and-upload path. **The preview page itself
is expected not to load in a browser:** the asset CDN only allows the
staging and production origins in its CORS rules, so module scripts are
blocked on a `*.vercel.app` URL.
- In the build log, check `Uploading immutable static files to R2...` is
followed by `Upload completed successfully!`
- View the preview's page source: the `<script>`, `modulepreload` and
stylesheet tags point at the staging asset CDN
(`.../<SITE_NAME>/tanstack/_vercel/immutable/...`) with
`crossorigin="anonymous"`
- Open a few of those asset URLs directly in a new tab (a JS chunk, a
CSS file, and a `.woff2` font from the CSS): each returns 200 with the
right content type
- Worker URLs inside the chunks still point at
`/dashboard/_vercel/immutable/.../*.worker-*.js` on the page's own
origin
### After merge, on the full staging environment
- Load the staging dashboard with DevTools open: every script,
modulepreload and stylesheet comes from the staging asset CDN with a
200, and there are no CORS or CSP errors in the console
- Fonts render (Inter, and the code fonts in the SQL editor)
- Sign in and click around: Table Editor, SQL Editor, GraphiQL, Logs.
Lazy routes load, and nothing comes from `/dashboard/_vercel/immutable`
except Monaco's workers
- SQL Editor and GraphiQL: Monaco works (syntax highlighting,
autocomplete), and its workers load same-origin
- Trigger an error and check the Sentry event has a readable stack trace
- After the next staging deploy, check the build log's upload only added
new files
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
132 lines
5.6 KiB
Bash
Executable File
132 lines
5.6 KiB
Bash
Executable File
#!/bin/bash
|
|
set -eo pipefail
|
|
|
|
#######
|
|
|
|
# This script is used to upload static build assets (JS, CSS, ...) and public static files (public folder) to a CDN.
|
|
# We're using Cloudflare R2 as CDN.
|
|
# By using a CDN, we can serve static assets extremely fast while saving big time on egress costs.
|
|
# An alternative is proxying via CF, but that comes with Orange-To-Orange issues (Cloudflare having issues with Cloudflare) and increased latency as there is a double TLS termination.
|
|
# The script is only supposed to run on production deployments and is not run on any previews.
|
|
|
|
# By using a dynamic path including the env, app and commit hash, we can ensure that there are no conflicts.
|
|
# Static assets from previous deployments stick around for a while to ensure there are no "downtimes".
|
|
|
|
# Advantages of the CDN approach we're using:
|
|
|
|
# Get rid of egress costs for static assets across our apps on Vercel
|
|
# Disable CF proxying and get around these odd timeouts issues
|
|
# Save ~20ms or so for asset requests, as there is no additional CF proxying and we avoid terminating SSL twice
|
|
# Always hits the CDN, gonna be super quick
|
|
# Does not run on local or preview environments, only on staging/prod deployments
|
|
# There are no other disadvantages - you don't have to consider it when developing locally, previews still work, everything on Vercel works as we're used to
|
|
|
|
#######
|
|
|
|
# If asset CDN is specifically disabled (i.e. studio self-hosted), we skip
|
|
if [[ "$FORCE_ASSET_CDN" == "-1" ]]; then
|
|
echo "Skipping asset upload. Set FORCE_ASSET_CDN=1 or VERCEL_ENV=production to execute."
|
|
exit 0
|
|
fi
|
|
|
|
# Check for force env var or production environment
|
|
if [[ "$FORCE_ASSET_CDN" != "1" ]] && [[ "$VERCEL_ENV" != "production" ]]; then
|
|
echo "Skipping asset upload. Set FORCE_ASSET_CDN=1 or VERCEL_ENV=production to execute."
|
|
exit 0
|
|
fi
|
|
|
|
# The build already points at the CDN at this point, so a missing credential
|
|
# must fail the build rather than skip the upload.
|
|
for var in ASSET_CDN_S3_ENDPOINT AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY; do
|
|
if [[ -z "${!var}" ]]; then
|
|
echo "Asset CDN upload is enabled but $var is not set. Set the R2 credentials for this environment, or FORCE_ASSET_CDN=-1 to disable the asset CDN."
|
|
exit 1
|
|
fi
|
|
done
|
|
|
|
# Set the cdnBucket variable based on NEXT_PUBLIC_ENVIRONMENT
|
|
if [[ "$NEXT_PUBLIC_ENVIRONMENT" == "staging" ]]; then
|
|
BUCKET_NAME="frontend-assets-staging"
|
|
else
|
|
BUCKET_NAME="frontend-assets-prod"
|
|
fi
|
|
|
|
STATIC_DIR=".next/static"
|
|
PUBLIC_DIR="public"
|
|
|
|
# Colors for output
|
|
GREEN='\033[0;32m'
|
|
YELLOW='\033[1;33m'
|
|
NC='\033[0m' # No Color
|
|
|
|
# Install AWS CLI if not present
|
|
if ! command -v aws &> /dev/null; then
|
|
echo -e "${YELLOW}Setting up AWS CLI...${NC}"
|
|
curl -s "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.22.35.zip" -o "awscliv2.zip"
|
|
unzip -q awscliv2.zip
|
|
export PATH=$PWD/aws/dist:$PATH
|
|
rm awscliv2.zip
|
|
fi
|
|
|
|
# TanStack Start builds (Studio): upload Nitro's Vercel immutable store, whose
|
|
# files are content-hashed, to a folder shared by every deployment (see
|
|
# apps/studio/asset-cdn.ts). Shared rather than per-commit so unchanged chunks
|
|
# dedupe and older tabs keep resolving their lazy chunks. The files also stay in
|
|
# the Vercel output: web workers must be served same-origin.
|
|
if [[ "$1" == "tanstack" ]]; then
|
|
IMMUTABLE_DIR=".vercel/output/static/_vercel/immutable"
|
|
if [ ! -d "$IMMUTABLE_DIR" ]; then
|
|
echo -e "${YELLOW}Directory $IMMUTABLE_DIR not found!${NC}"
|
|
echo "Make sure the TanStack build ran for Vercel with immutable static files enabled."
|
|
exit 1
|
|
fi
|
|
|
|
# Names are content hashes, so an existing object never needs replacing:
|
|
# --size-only skips files a previous deployment already uploaded (the
|
|
# default mtime check would re-upload every freshly built file). Source
|
|
# maps are uploaded to Sentry, never published.
|
|
echo -e "${YELLOW}Uploading immutable static files to R2...${NC}"
|
|
aws s3 sync "$IMMUTABLE_DIR" "s3://$BUCKET_NAME/${SITE_NAME:-studio}/tanstack/_vercel/immutable" \
|
|
--size-only \
|
|
--exclude "*.map" \
|
|
--endpoint-url "$ASSET_CDN_S3_ENDPOINT" \
|
|
--cache-control "public,max-age=31536000,immutable" \
|
|
--region auto \
|
|
--only-show-errors
|
|
|
|
echo -e "${GREEN}Upload completed successfully!${NC}"
|
|
exit 0
|
|
fi
|
|
|
|
# Check if directory exists
|
|
if [ ! -d "$STATIC_DIR" ]; then
|
|
echo -e "${YELLOW}Directory $STATIC_DIR not found!${NC}"
|
|
echo "Make sure you're running this script from your Next.js project root."
|
|
exit 1
|
|
fi
|
|
|
|
# Upload files with cache configuration and custom endpoint
|
|
echo -e "${YELLOW}Uploading static files to R2...${NC}"
|
|
aws s3 sync "$STATIC_DIR" "s3://$BUCKET_NAME/$SITE_NAME/${VERCEL_GIT_COMMIT_SHA:0:12}/_next/static" \
|
|
--endpoint-url "$ASSET_CDN_S3_ENDPOINT" \
|
|
--cache-control "public,max-age=604800,immutable" \
|
|
--region auto \
|
|
--only-show-errors
|
|
|
|
# Some public files may be referenced through CSS (relative path) and therefore they would be requested via the CDN url
|
|
# To ensure we don't run into some nasty debugging issues, we upload the public files to the CDN as well
|
|
echo -e "${YELLOW}Uploading public files to R2...${NC}"
|
|
aws s3 sync "$PUBLIC_DIR" "s3://$BUCKET_NAME/$SITE_NAME/${VERCEL_GIT_COMMIT_SHA:0:12}" \
|
|
--endpoint-url "$ASSET_CDN_S3_ENDPOINT" \
|
|
--cache-control "public,max-age=604800,immutable" \
|
|
--region auto \
|
|
--only-show-errors
|
|
|
|
echo -e "${GREEN}Upload completed successfully!${NC}"
|
|
|
|
# Clean up local static files so we prevent a double upload
|
|
echo -e "${YELLOW}Cleaning up local static files...${NC}"
|
|
rm -rf "$STATIC_DIR"/*
|
|
echo -e "${GREEN}Local static files cleaned up${NC}"
|
|
|
|
# We still keep the public dir, as Next.js does not officially support serving the public files via CDN |