From 941eee914274824c922404d6e1e242bb28edc84b Mon Sep 17 00:00:00 2001 From: multipleof4 Date: Fri, 26 Sep 2025 15:37:13 -0700 Subject: [PATCH] Fix: Allow Pages to handle static root by calling next() --- functions/[[path]].js | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/functions/[[path]].js b/functions/[[path]].js index 76d49fa..8e88591 100644 --- a/functions/[[path]].js +++ b/functions/[[path]].js @@ -1,13 +1,33 @@ const C='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',L=4,H={'Access-Control-Allow-Origin':'*'} const r=()=>[...Array(L)].map(()=>C[Math.random()*C.length|0]).join('') -export async function onRequest({request, env}){ - if(request.method==='OPTIONS')return new Response(null,{headers:{...H,'Access--Allow-Methods':'POST','Access-Control-Allow-Headers':'Content-Type'}}) - const u=new URL(request.url),p=u.pathname.slice(1) +export async function onRequest({request, env, next}){ + if(request.method==='OPTIONS')return new Response(null,{headers:{...H,'Access-Control-Allow-Methods':'POST','Access-Control-Allow-Headers':'Content-Type'}}) - if(request.method==='POST' && !p){try{let{url:t}=await request.json();new URL(t);let s;do s=r();while(await env.EV.get(s)!=null);await env.EV.put(s,t);const d={slug:s,target:t,shortUrl:`${u.origin}/${s}`};return new Response(JSON.stringify(d),{headers:{'Content-Type':'application/json',...H}})}catch(e){return new Response('Invalid URL',{status:400,headers:H})}} + const u=new URL(request.url) - if(p){const t=await env.EV.get(p);if(t)return Response.redirect(t,302)} - - return new Response('Not Found',{status:404,headers:H}) + // Handle POST request to create a link (API call) + if(u.pathname==='/'&&request.method==='POST'){ + try{ + const{url:t}=await request.json(); + new URL(t); + let s; + do s=r();while(await env.EV.get(s)); + await env.EV.put(s,t); + const d={slug:s,target:t,shortUrl:`${u.origin}/${s}`}; + return new Response(JSON.stringify(d),{headers:{'Content-Type':'application/json',...H}}) + }catch(e){ + return new Response('Invalid URL',{status:400,headers:H}) + } + } + + // Handle GET request for a slug (Redirect) + const p=u.pathname.slice(1) + if(p){ + const t=await env.EV.get(p) + if(t)return Response.redirect(t,302) + } + + // For all other requests (like GET /), pass them to the static asset handler. + return next() }