braincel
braincel
Explore posts from servers
CDCloudflare Developers
Created by braincel on 10/2/2024 in #pages-help
Easiest way of persisting function logs
No description
1 replies
CDCloudflare Developers
Created by braincel on 9/28/2024 in #pages-help
How to point CF domain to CF pages project
No description
8 replies
CDCloudflare Developers
Created by braincel on 8/8/2024 in #pages-help
ReferenceError: XMLHttpRequest is not defined on api endpoint
I'm deploying a NextJS project using next on pages. I'm getting a "ReferenceError: XMLHttpRequest is not defined" when trying to run the code block below. It sounds like the worker behind the pages is trying to use XMLHttpRequest instead of the normal fetch? How do i fix this?
async function getSpotifyTokens(
clientId: string,
clientSecret: string,
) {
const tokenUrl = 'https://accounts.spotify.com/api/token'
const authStr = `${clientId}:${clientSecret}`
const b64AuthStr = Buffer.from(authStr).toString('base64')

const headers = {
Authorization: `Basic ${b64AuthStr}`,
'Content-Type': 'application/x-www-form-urlencoded',
}
// const body = new URLSearchParams({
// grant_type: 'client_credentials',
// })
const body = 'grant_type=client_credentials'

const response = await fetch(tokenUrl, {
method: 'POST',
headers,
body,
})

if (!response.ok) {
const errorText = await response.text()
throw new Error(`Failed to get token: ${response.status} - ${errorText}`)
}

const tokens = (await response.json()) as ExtendedGetRefreshedAccessTokenResponse
return tokens
}
async function getSpotifyTokens(
clientId: string,
clientSecret: string,
) {
const tokenUrl = 'https://accounts.spotify.com/api/token'
const authStr = `${clientId}:${clientSecret}`
const b64AuthStr = Buffer.from(authStr).toString('base64')

const headers = {
Authorization: `Basic ${b64AuthStr}`,
'Content-Type': 'application/x-www-form-urlencoded',
}
// const body = new URLSearchParams({
// grant_type: 'client_credentials',
// })
const body = 'grant_type=client_credentials'

const response = await fetch(tokenUrl, {
method: 'POST',
headers,
body,
})

if (!response.ok) {
const errorText = await response.text()
throw new Error(`Failed to get token: ${response.status} - ${errorText}`)
}

const tokens = (await response.json()) as ExtendedGetRefreshedAccessTokenResponse
return tokens
}
here's the dev branch of my site: https://dev.cf-next-cpa.pages.dev/ The endpoint in question is this: https://dev.cf-next-cpa.pages.dev/api/spotify_auth/refresh_tokens ----- The funny thing about this though is that my code has been running perfectly fine before this (for like 400+ commits/deploys) then all of a sudden it stopped working now. I'm also using supabase but it doesn't seem to be the issue since the error only occurs exactly at the fetch call. Did something change with CF workers? The code works just fine locally btw ,also i use the pages dir instead of the app dir.
14 replies
CDCloudflare Developers
Created by braincel on 1/1/2024 in #general-help
Help with DNS resolution (using CF pages and CF domain name)
I currently have my site hosted using CF pages and bought a domain using CF's registrar, it works fine and all for the most part where if i type domain.app, it displays the contents I have deployed using CF pages (i set this up using pages' "custom domains") after i set this up tho, there was this notice on the dashboard saying something like i have to set up the A,AAAA and CNAME records such that www.domain.app would also redirect to domain.app so i tried (as seen on the screenshot) but it didn't work what'd i do wrong? (it's my first time dealing with domains so i'm pretty unfamiliar with these stuff) btw, the CNAME record here is the record automatically set by CF after i linked the domain name to my pages project
6 replies
TTCTheo's Typesafe Cult
Created by braincel on 10/25/2023 in #questions
AI copilot/code intellgience
does anyone know of a code intelligence/AI copilot thing but with embeddings (i.e. takes your codebase as context), something kind of AI i can ask questions when i want to but takes into account my codebase as context (not AI autocomplate) i know sourcegraph does this, but i remember seeing another program on YT but couldn't remember its name (it's not Kite/Copilot/Tabnine)
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 9/19/2023 in #questions
Just a question about the current state of Next's app router
Almost every new video on YT rn uses the app router instead of pages. I was initially hesitant to switch to app because of some caching issues, but a lot of libraries rn (like clerk and supabase) have been favoring app over pages. I'm just wondering, have the caching issues been fixed? It's the only thing holding me back anyway.
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 8/26/2023 in #questions
postgres(i.e. supabase) functions and triggers with drizzle ORM
i'm about to start leaning drizzle (can't use prisma because i deploy to a full-edge environment). before i dive deep into drizzle though, i'm wondering, how does one handle/create functions triggers using drizzle? doesn't seem like something one would put inside the schema file. couldn't find info on their docs either
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 7/16/2023 in #questions
Paypal webhooks
I've successfully set up paypal subscriptions inside a nextJS app whenever i subscribe using the paypal buttons, it works just fine, but the only event that's fired is BILLING.SUBSCRIPTION.ACTIVATED if i have my subscriptions be billed monthly, should i wait one month for the PAYMENT.SALE.COMPLETED event? i was expecting both BILLING.SUBSCRIPTION.ACTIVATED and PAYMENT.SALE.COMPLETED would fire when a user first subscribes, then PAYMENT.SALE.COMPLETED for the next payments Is it normal behavior for that only BILLING.SUBSCRIPTION.ACTIVATED is fired at first, and (maybe) only subsequent payments are PAYMENT.SALE.COMPLETED ? or have i misconfigured my subscriptions or something? (though afaik, i did just a simple subscription)
3 replies
TTCTheo's Typesafe Cult
Created by braincel on 7/13/2023 in #questions
Clerk auth 'authMiddleware' vs 'withClerkMiddleware' and setting cookies
(https://clerk.com/docs/nextjs/middleware) I'm trying to set two cookies inside authMiddleware (afterAuth) and it works for setting the first cookie, but any subsequent cookies aren't set at all. If i try to do it using the older 'withClerkMiddleware', it works tho. i'm doing it simply like:
const res = NextResponse.next()
res.cookies.set('cookie1', 'cookie1')
res.cookies.set('cookie2', 'cookie2')
const res = NextResponse.next()
res.cookies.set('cookie1', 'cookie1')
res.cookies.set('cookie2', 'cookie2')
is there a way to set two cookies using authMiddeware? i'm fine with using withClerkMiddleware but there's a deprecation warning What exactly happens when the method is deprecated? Will it stop working?
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 7/11/2023 in #questions
Google sheets API and restricting scopes
Is it possible to somehow restrict API use to only creation/updating of google sheets? I'm currently referencing this (https://developers.google.com/identity/protocols/oauth2/scopes#sheets) and it seems like the only options are either readonly, or full control of files, it'd be nice to be able to specify more granular control/limits to the file manipulation.
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 7/10/2023 in #questions
Clerk and provider access / refresh tokens
I'm currently using supabase for auth. One thing i found lacking though is that it doesn't automatically refresh the provider's (.e.g google) refresh token. I've already tried nextauth and afaik nextauth doesn't have this funcionality as well. So i googled if this is something clerk can handle, found this (https://clerk.com/docs/authentication/social-connections-oauth#o-auth-access-token-wallet ). Just wanted to confirm that as the docs say, whatever OAuth provider i use, i use call this endpoint (https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetOAuthAccessToken ) and clerk will give me an access token from the provider, while handling the refreshing of the tokens if necessary?
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/29/2023 in #questions
Paypal webhooks with NEXT's edge runtime
I'm currently testing paypal webhooks locally and it runs just fine on the normal runtime but when i turn on edge, i can't get the body of the request (in particular webhook_event which is necessary for this: https://developer.paypal.com/docs/api/webhooks/v1/#verify-webhook-signature_post ) any ideas why i can't get the body at all when using edge?
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/18/2023 in #questions
Paypal subscriptions: how to verify successful sandbox payment
i'm currently experimenting with paypal + nextjs for subscriptions i think i got it right so far code goes something like this:
<PayPalButtons
createSubscription={async (data, actions) => {
const res = await myFetch(
'/api/payment/create_subscription',
{
method: 'POST',
},
)

return actions.subscription
.create({
plan_id: res.id,
})
.then((orderId) => {
return orderId
})
}}
onApprove={async (data, actions) => {
toast.success(`Subscription payment success! : ${data.subscriptionID}`)
}}
/>
<PayPalButtons
createSubscription={async (data, actions) => {
const res = await myFetch(
'/api/payment/create_subscription',
{
method: 'POST',
},
)

return actions.subscription
.create({
plan_id: res.id,
})
.then((orderId) => {
return orderId
})
}}
onApprove={async (data, actions) => {
toast.success(`Subscription payment success! : ${data.subscriptionID}`)
}}
/>
looks like it worked how do i check if the payment is successful tho? (can't find any info on the developer sandbox accounts about any ongoing subscriptions) (i can't use stripe where i live btw)
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/12/2023 in #questions
Nextjs (edge runtime) logging provider/library for prod
what's a nice logging solution for working with nextjs edge ? (CF pages/workers in paritcular) i haven't try logging in prod yet so this is very new to me. I've heard of sentry but i'm not sure of the other options. Most of the free(?) solutions i've found are libraries (pino and winston?) but they're for node. I can't use node tho because of edge.
8 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/11/2023 in #questions
NEXT edge api routes: sending a json response
I'm currently migrating my app to work with edge worked fine so far until i tried to return json to the frontend, then the frontend was complaining with SyntaxError: Unexpected end of JSON input I just followed the examples from nextjs guide (pages router in particular), but it seems this isn't the right way to send json to the frontend, how should i do it? edge runtime code:
const responseBody = JSON.stringify({
accessToken: newAccessToken,
refreshToken: newRefreshToken ?? '',
expiresAt: Date.now() + 3600 * 1000,
})

return new Response(responseBody, {
status: 200,
headers: {
'content-type': 'application/json',
},
})
const responseBody = JSON.stringify({
accessToken: newAccessToken,
refreshToken: newRefreshToken ?? '',
expiresAt: Date.now() + 3600 * 1000,
})

return new Response(responseBody, {
status: 200,
headers: {
'content-type': 'application/json',
},
})
It's erroring out on this part in particular(on the frontend):
const { accessToken, expiresAt } = await fetch('/api/......', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refreshToken }),
})
.then((res) => {
return res.json() // -<<<<<< It's ERRORING HERE
})
.then((d) => {
return d
})
const { accessToken, expiresAt } = await fetch('/api/......', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refreshToken }),
})
.then((res) => {
return res.json() // -<<<<<< It's ERRORING HERE
})
.then((d) => {
return d
})
3 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/8/2023 in #questions
Can i front a (non-prod) netlify(or other providers) app with cloudflare?
Netlify has just been blocked where i live, i can't access any site with **.netlify.app Is it possible to add my development site such that it proxies to cloudflare for now? If i'm right, i would(might) be able to access my netlify site right? I did try adding the site for now but it's a bit confusing rn, all the instructions i've found seem to indicate that i need to buy a domain name first. So i was wondering if it's possible to do without having to buy a domain name first.
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 6/8/2023 in #questions
proper edge-to-edge setup (i.e. CF workers, regions, and edge auth (with supabase))
What's the proper architecture/setup for an edge function calling another edge function? -------- i'm currently playing around with CF workers and they've been really nice so far. I've been wondering tho, if i'm right, i think CF workers are deployed globally by default and the functions pop up as close to the user as possible right? I was wondering if it's possible to set them to regional, similar to vercel's edge (it prob is possible but i haven't found much info, prob because this is vercel's trade secret or something). On the other hand, it might not even be necessary to replicate vercel's regional edge functions. Afaik (correct me if i'm wrong), regional edge is only necessary if the DB is only constrained to one location. If i use supabase edge for auth and DB calls (e.g. checking that the user is signed in on every call, checking their payment status, etc), my intuition tells me that i'll have nothing to worry about because the app flow would prob be something like this:
-> frontend makes request to edge CF worker
-> a CF worker spins up closest to the user
-> CF worker calls a supabase edge function
-> Supabase edge function spins up closest to where the CF worker was
-> frontend makes request to edge CF worker
-> a CF worker spins up closest to the user
-> CF worker calls a supabase edge function
-> Supabase edge function spins up closest to where the CF worker was
Therefore i'll have nothing to worry about if an edge function calls another edge function because they'll always be close to each other? I'm pretty new to edge so i'm not sure if this is right, do i have something i should keep in mind when working with edge?
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 5/26/2023 in #questions
Figma/SVG vs D3 vs other libraries for programmatically generating music/chord charts
I haven't tried creating SVGs yet or D3 (or any charting library) so i'm not really sure what route i should go with but, what would be a relatively easy path for generating charts like the attached picture? (i'll also have to color the sectors dynamically) I'll also be making custom piano chord/scale charts (ping me)
3 replies
TTCTheo's Typesafe Cult
Created by braincel on 5/18/2023 in #questions
react query persistQueryClient: store each queryKey/queryHash in its own IDB k-v row
I'm currently using react query to persist some queries to indexedDB (a lot of queries, so i can't use localStorage because it's limited to 5mb) I noticed that RQ stores all of the queries in one single k-v. it it possible to set the persister to store each queryKey/Hash on its own k-v row? Having them all inside one row makes it a bit harder to debug since now during dev, i periodically check if my cache is actually correct or not. -- I'm also curious if this is the right approach to persist some of my queries, maybe ya'll might have other suggestions. Reference: https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient#building-a-persister
2 replies
TTCTheo's Typesafe Cult
Created by braincel on 4/26/2023 in #questions
Need advice on SVGs for creating custom shapes for react/next
I'll be creating some custom shapes (e.g. custom maps, math/geometry illustrations) for a react app and i remember from somewhere that SVGs might be the best way to handle those. What would be a good way of going about this for someone new to SVGs in webdev? The current workflow i have in mind would be to learn figma (i already know photoshop so i guess the learning curve would be a bit less steep). Then use figma to create the shapes, export them for use in react? Do i need to use a library? D3 maybe? (although fwik, D3 is used mostly for charts and has a steep learning curve)
4 replies