Proxy to cloudfront for local development without all the images

This commit is contained in:
2026-04-17 22:35:23 -07:00
parent 72eca0a76a
commit 6be4af58b4

View File

@@ -1,9 +1,60 @@
import { defineConfig } from "vite-plus"; import { defineConfig } from "vite-plus";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import { stat } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
const rootDir = path.dirname(fileURLToPath(import.meta.url)); const rootDir = path.dirname(fileURLToPath(import.meta.url));
const imageRootDir = path.resolve(rootDir, "img");
const imageFallbackBase = "https://ski.aarongutierrez.com";
const fileExists = async (filename: string): Promise<boolean> => {
try {
await stat(filename);
return true;
} catch {
return false;
}
};
const imageFallbackMiddleware = async (
req: { method?: string; url?: string },
res: { statusCode: number; setHeader: (name: string, value: string) => void; end: () => void },
next: () => void,
): Promise<void> => {
if ((req.method !== "GET" && req.method !== "HEAD") || !req.url) {
next();
return;
}
const requestUrl = new URL(req.url, "http://localhost");
const pathname = decodeURIComponent(requestUrl.pathname);
if (!pathname.startsWith("/img/")) {
next();
return;
}
const relativePath = pathname.slice(1);
const localFile = path.resolve(rootDir, relativePath);
const relativeToImageRoot = path.relative(imageRootDir, localFile);
const isWithinImageRoot =
relativeToImageRoot !== "" &&
relativeToImageRoot !== ".." &&
!relativeToImageRoot.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativeToImageRoot);
if (!isWithinImageRoot || (await fileExists(localFile))) {
next();
return;
}
const fallbackUrl = new URL(pathname, imageFallbackBase);
fallbackUrl.search = requestUrl.search;
res.statusCode = 302;
res.setHeader("Location", fallbackUrl.toString());
res.end();
};
export default defineConfig({ export default defineConfig({
staged: { staged: {
@@ -28,6 +79,15 @@ export default defineConfig({
} }
}, },
}, },
{
name: "image-fallback-to-production",
configureServer(server) {
server.middlewares.use(imageFallbackMiddleware);
},
configurePreviewServer(server) {
server.middlewares.use(imageFallbackMiddleware);
},
},
], ],
resolve: { resolve: {
alias: { alias: {