OATUH Cloudflare Pages

I was developing trying to implement github oauth on cloudfare pages using a beta branch. the production branch is define as another branch and the production branch contains the main url. It works locally but not on cloudflare pages my oauth flow looks like this at the moment
export async function GET(context: APIContext): Promise<Response> {
const state = generateState();
const url = await github.createAuthorizationURL(state);

context.cookies.set("github_oauth_state", state, {
path: "/",
secure: DEPLOYED_ENV,
httpOnly: true,
maxAge: 60 * 10,
sameSite: "lax"
});

const responseBody = {
url: url.toString()
};
const response = new Response(JSON.stringify(responseBody), {
status: 200,
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*"
}
});
return response;
}
export async function GET(context: APIContext): Promise<Response> {
const state = generateState();
const url = await github.createAuthorizationURL(state);

context.cookies.set("github_oauth_state", state, {
path: "/",
secure: DEPLOYED_ENV,
httpOnly: true,
maxAge: 60 * 10,
sameSite: "lax"
});

const responseBody = {
url: url.toString()
};
const response = new Response(JSON.stringify(responseBody), {
status: 200,
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*"
}
});
return response;
}
19 Replies
sanner
sannerOP3mo ago
Frontend
async function handleAuth() {
let realHref: string = href;
try {
const response = await fetch(realHref, { credentials: "include" });
const jsonResponse = await response.json();
let url = jsonResponse.url;
realHref = url;
console.log(jsonResponse);
if (url.includes("google")) {
realHref = addGoogleRedirectUri(url);
}
window.location.replace(realHref);
} catch (error) {
console.log(error);
}
}
async function handleAuth() {
let realHref: string = href;
try {
const response = await fetch(realHref, { credentials: "include" });
const jsonResponse = await response.json();
let url = jsonResponse.url;
realHref = url;
console.log(jsonResponse);
if (url.includes("google")) {
realHref = addGoogleRedirectUri(url);
}
window.location.replace(realHref);
} catch (error) {
console.log(error);
}
}
callback
context.cookies.set("auth-session", cookieString, {
path: "/",
secure: DEPLOYED_ENV,
httpOnly: true,
maxAge: 60 * 10,
sameSite: "lax"
});
await setUserSession(
cookieString,
{
username_tag: userId,
profile_picture_url: googleUser.picture,
}
).catch((error) => {
console.error(error);
return new Response("Unable to set user session", {
status: 500,
});
});
return context.redirect("/postsignup");
context.cookies.set("auth-session", cookieString, {
path: "/",
secure: DEPLOYED_ENV,
httpOnly: true,
maxAge: 60 * 10,
sameSite: "lax"
});
await setUserSession(
cookieString,
{
username_tag: userId,
profile_picture_url: googleUser.picture,
}
).catch((error) => {
console.error(error);
return new Response("Unable to set user session", {
status: 500,
});
});
return context.redirect("/postsignup");
Chaika
Chaika3mo ago
and you get an error deployed? It blows up? Need more info on what exactly happens, if I had to guess most OAuth setups require you to specify valid callback urls/returns in the setup and you didn't add the pages.dev/custom domain (whichever one you're using) but you just haven't provided enough info
sanner
sannerOP3mo ago
So the main issue is, is that the oauth workflow works on localhost but not when deployed on cloudflare to the non-main branch. The main branch has a static url for both deployment url's the branch or link I am testing on does not have a static url but it does have a static alias The callback url is set to the alias url generated by cloudflare as opposed to the numeric url set to the branch.
Chaika
Chaika3mo ago
ok and when it doesn't work, what happens? The function throws an error? Github throws an oauth error?
sanner
sannerOP3mo ago
There is not necessarily an error it seems that the callback route is unable to be accessed on cloudflare, in the sense that a 404 is thrown when the callback is accesssed I was thinking of potentially switching to hono with cloudflare which will allow me to mitigate many of these issues
Chaika
Chaika3mo ago
Hono vs normal functions routing can still accomplish the same, hono might be easier to work with if you're coming from express or something. You're not great at providing info though, which makes this super hard. Your callback is just being handled in your front end logic, and for some reason isn't matching? What's your local setup using/what framework/etc?
sanner
sannerOP3mo ago
I am using astro and the code is being invoked in a client side rendered svelte portion running inside astro within a pages directory which is typically used for routing in astro
Chaika
Chaika3mo ago
Are you trying to use the Cloudflare adapter or just a fully static generated astro setup?
sanner
sannerOP3mo ago
I am using a cloudflare adapater with hybrid rendering
Chaika
Chaika3mo ago
hmm yea that uses the Cloudflare adapter which uses advanced mode and would conflict with normal functions
sanner
sannerOP3mo ago
For further context I have not used hono yet, though I intended to, currently I am using calling the api routes which are under the pages directory.
Chaika
Chaika3mo ago
yea that's what I mean, you'd have to make a seperate worker to use hono, not going to be able to do astro in cf adapter mode + hono in same project, it (astro cf adapter) uses advanced mode functions the routing issue is curious, I would tail the function and show uploaded files. I'm not too familiar with Astro, they have an active Discord though if you could boil it down to "I have this Astro site with these files and this Astro API Route". There is some interesting info here: https://docs.astro.build/en/guides/endpoints/#server-endpoints-api-routes about opting API Routes outside of prerendering in hybrid mode (although based off what you've said, seems like not your issue..?) I would also try previewing locally with wrangler to try to repro outside of deployments: https://docs.astro.build/en/guides/integrations-guide/cloudflare/#preview-with-wrangler
sanner
sannerOP3mo ago
why is that you are unable to interoperate hono+astro in a single hono project. I was looking at a tutorial in astro + hono on cloudflare. 4
sanner
sannerOP3mo ago
GitHub
astro-hono-example/src/lib/api/index.ts at main · bmdavis419/astro-...
Basic example of a hono server working with astro DB and astro - bmdavis419/astro-hono-example
sanner
sannerOP3mo ago
Though the fellow uses vercel and hono as the adapter, now that I look at it again
Chaika
Chaika3mo ago
Astro's Adapter uses Functions Advanced mode: https://developers.cloudflare.com/pages/functions/advanced-mode/ Which skips all of the path based routing/middleware/etc and basically takes over all routing/requests, and you can't have two of those
Cloudflare Docs
Advanced mode | Cloudflare Pages docs
Advanced mode allows you to develop your Pages Functions with a _worker.js file rather than the /functions directory.
Chaika
Chaika3mo ago
..unless you made Astro static generate/not use the cf adapter
sanner
sannerOP3mo ago
Thanks I guess I will look into and reevaluate whether to host my auth server on astro or worker+hono
ethereon
ethereon3mo ago
Following up on this, what he means is that he's not using the front end logic to host auth. He's using astro as a backend and only having auth from the server-side so Astro really has nothing to do with it
Want results from more Discord servers?
Add your server