From 5b11299a0c5560624edf261a30bcb601851617dc Mon Sep 17 00:00:00 2001 From: Arun Date: Fri, 26 Jan 2024 20:16:39 -0800 Subject: [PATCH] Update Static Publisher for JavaScript to redirect apex domain to www version and give another shot at GitHub action for deployment working --- .github/workflows/deploy.yml | 6 +++++- compute-js/src/index.js | 29 ++++++++++++++++++++++------- tsconfig.json | 5 ++++- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 2e01817b..f3ab59cd 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -15,6 +15,10 @@ jobs: - name: Build project run: npm run build + deploy: + needs: build + runs-on: ubuntu-latest + steps: - name: Install Fastly dependencies run: npm install working-directory: ./compute-js @@ -22,7 +26,7 @@ jobs: - name: fastly compute deploy uses: fastly/compute-actions@v5 with: - project_directory: “compute-js” + project_directory: compute-js comment: “Deployed via GitHub Actions” env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} diff --git a/compute-js/src/index.js b/compute-js/src/index.js index 7c7bd5b7..989c66fa 100644 --- a/compute-js/src/index.js +++ b/compute-js/src/index.js @@ -1,18 +1,33 @@ /// -import { getServer } from '../static-publisher/statics.js'; +import { getServer } from "../static-publisher/statics.js"; const staticContentServer = getServer(); -// eslint-disable-next-line no-restricted-globals addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); + async function handleRequest(event) { + const req = event.request; + const host = req.headers.get("Host"); + + // Check for apex domain and redirect to www + if (host && !host.startsWith("www.")) { + const redirectURL = new URL(req.url); + redirectURL.hostname = `www.${host}`; - const response = await staticContentServer.serveRequest(event.request); + return new Response(null, { + headers: { + Location: redirectURL.toString(), + "Cache-Control": "max-age=86400", + }, + status: 301, + }); + } + + // Serve static content + const response = await staticContentServer.serveRequest(req); if (response != null) { return response; } - // Do custom things here! - // Handle API requests, serve non-static responses, etc. - - return new Response('Not found', { status: 404 }); + // Return a 404 response if the content is not found + return new Response("Not found", { status: 404 }); } diff --git a/tsconfig.json b/tsconfig.json index 77da9dd0..2bb8f8e0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,3 +1,6 @@ { - "extends": "astro/tsconfigs/strict" + "extends": "astro/tsconfigs/strict", + "exclude": [ + "compute-js" + ] } \ No newline at end of file