Next.js Discord

Discord Forum

Stripe Checkout App Router - CORS

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
const StripeCheckOutButton :React.FC<StripeCheckOutButtonProps> = ({product_id,user,price_id}) => {
  
  const handleCheckout = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
      const stripe = await getStripe();
      const response = await fetch("/api/create-checkout-session/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        cache: "no-cache",
        body: JSON.stringify({'product':product_id}),
      });

      const data = await response.json();
      if (data.session) {
        stripe?.redirectToCheckout({ sessionId: data.session.id });
      }
    };
  useEffect(() => {
    
  },[])

  return (
    <div className="py-5">
      <button
        className="bg-green-500 py-3 px-3 rounded-md"
        onClick={()=>handleCheckout}
      >
        Check out
      </button>
    </div>
  );
};

this is the button that directs to checkout
import { loadStripe, Stripe } from '@stripe/stripe-js';

let stripePromise: Promise<Stripe | null>;

export const getStripe = () => {
    if (!stripePromise) {
        stripePromise = loadStripe(
            process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY_LIVE ??
            process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ??
            ''
        );
    }

    return stripePromise;
};
this is how im loading stripe in a util/stripe-client.ts file , ```import Stripe from 'stripe';

more coming

115 Replies

Sun bearOP
`
the checkout button is a client component, i know theres other errors to fix but I've been tinkering with the cors error first so I can identify those errors - @DirtyCajunRice | AppDir
lemme link my repo if that may help, its messy right now because ive been tinkering to figure out what works
but still easy to follow
i feel like this is a huge clue because it keeps popping up every 30 seconds or so
im just re-learning nextjs with the app router so go easy on me
ok so I know where that first error is coming from, its from the getStripe() in the layout file . this is what happens when i try to click checkout
oh wow. fucking spelled checkout wrong
after tweaking those minor things, this is what happens when I click checkout
you know what, I think i may have just rubber ducked myself into figuring out the problem lol. One of the disadvantages of working alone as a fairly new person to the field
thanks for accompanying me on this ADHD fueled thought journey 😄
“ADHD: Its not a skill its a compulsion” - what i tell my wife
ok reading
Sun bearOP
haha yeah it is
gonna give you side notes as i read through this
Sun bearOP
appreciate it dude
Near gave a solid point that FC is not actually the right answer most of the time as the definition, and its better to just type the props
Sun bearOP
mmhm .. listening so dont let me interrupt
so instead do
({ your destructured shit here }): PropTypeDef)
i dont like the way it looks anymore than anyone else but its more accurate
Sun bearOP
yeah ive seen it done two different ways
the most recent one was the React.FC way
I used to do it exclusively that way
secondly, dont clutter your imports with React
Sun bearOP
noted
import { FC } from "react"
cleaner and less global injection muddle
Sun bearOP
yeah, ive been doing alot of "rafce" ing
i really appreciate this btw
it is so hard to get feedback that's not denigrating
I am never mean or nice about it. I am just blunt and some people are snowflakes and others take and learn from it haha
Sun bearOP
yeah i want the truth
i also dont want to be personally insulted , which is a balance most people dont strike
im perfectly fine with being corrected tho, i prefer it
making a joke without making it personal is a life long battle 😂
Sun bearOP
yeah and the text medium of the internet does it no favors
Ahhhh your cors error is solely localhost based!
have you tested it in production?
Sun bearOP
i actually took the getStripe() out of the layout file , and it stopped giving it to me - i had checkout spelled wrong
once i tweaked a few things, I just dont have the right data object going into the redirect
I had gotten this to work with Laravel
next is normally good about proxying the call to still work via localhost in dev, but some tools just wont work in dev
so its a crapshoot
Sun bearOP
yeah, ive been aware of the SSL requirements and how to test it
the stripe docs are very easy to read
the person im doing this site for, doesnt wanna pay for hosting that laravel will live on so I decided to use Next
which is why i couldnt understand why i was getting this error when I was able to do it in the other framework . but looks like i just overlooked too muich
i wouldnt do the top let stripe promise. The function should be all you need btw.
unless thats just leftover bloat
Sun bearOP
hm well I was modeling it after some other projects that Ive seen, they have a Stripe starter on the supabase website
and these functions were in the package at default
theyre set up more for subscription tho
@Sun bear hm well I was modeling it after some other projects that Ive seen, they have a Stripe starter on the supabase website
look at it the same way that next-auth gives an example for the mongodb client
lemme find the link
this is the right way to make a “global” client in next
without actually using globalThis
Sun bearOP
awesome .. im really grateful that you're being helpful without cutting me down as a person lol , I hesitate to ask for help alot because I end up getting into fights with people who condescend to me and accuse me of not trying or when i was in school, asking for my homework to be done, it was insulting and counter productive. That information is very useful
i dont get to actually talk to people who are interested in providing me help without also making sure their own ego is the dominant factor
Sun bearOP
yeah , ive got really thick skin
but also really strong principles about what i consider civilized behavior
Im close to 40 now, went back to school 5-6 years ago to get into this, went to school during the pandemic and kinda got cheated out of some of the experience i needed
so in the above example the let is used, but as a PROXY to global.
Sun bearOP
in the next auth ?
let client
yeah. the mongo code just pretend its ANY async client that you need multi access to
Sun bearOP
solid information
cause I know Ill definitely run into this again at some point
its using globalThis only within the scope of the file, and never accessing via global elsewhere. always using the func
basically as a “safety”
Sun bearOP
yeah definitely thats a principle I've got pretty ingrained in my knowledge, never use global config unless its absolutely necessary
the whole point of modularizing seems to be for that reason
necessary may be wrong word, appropriate
It gets more important in next because of the serverless nature of each page/api endpoint
since global isnt so permanent as people assume it is
Sun bearOP
yep yep, im wrapping my head around it. Yeah I remember when I first started on this stuff like 2 years ago and I was winging it, that was one of the early lessons about global variables and why to avoid using them. The thing about Next that has thrown me off the most is not really even Next itself, but Supabase (google firebase alternative) has createServerComponentClient and createClientComponentClient and it's hard to tell when to use which or if I need to use them
ive been trying to triangulate the docs, and 2 pretty thorough youtubers to learn it
I believe the syntactical thing you said before how you do it, is how Adrian of JSMastery does it, and this guy Antonio who does alot of Next13 App projects, was doing it this way. ANd thats the last person I watched before I did this
I have written in a LOT of languages over the years, so every now and then i get my best practices mixed up, but ive been having to do so much frontend work recently that i have gotten most of it “re” nailed down
Sun bearOP
Yeah that's been the bigggest challenge for me since I've been out of work, is to stick with one thing. I got a job directly after I graduated last year and wasnt given much training or support even though they knew who I was and what my experience was... Was Laravel/Nuxt based but I didnt have a team to work with, just one person
you have 8 years on me as the globe spins. Which is much closer than the majority of the discord at 18-22
Sun bearOP
yeah im not really worried about my age I actually consider it an assett
it is
Sun bearOP
the problem is my social circle is so small now
and I have no one to go to with stuff like this that I can rely on to tell me the truth
pride melts away with age and only “figuring the shit out” matters
Sun bearOP
yup
thats exactly where im at
@Sun bear the problem is my social circle is so small now
i dont think this gets better unfortunately
unless you are a slow learner
Sun bearOP
im a fast learner
when able to have a conversation like this
when someone is fighting with me about something semantical, its counter-productive
yeah. In my experience the circles are temporary. you goldfish grow to the size of your “tank” then you need to search for a bigger tank
Sun bearOP
yep. its been rough for me to do because of certain limitations ive had but those limitations are receding, and im honestly trying to make an effort to build a reality based social life
i dont make excuses
there are some VERY smart people in here though. So if you can weed through the randoms just giving an incorrect statement and vanishing there is a shit ton to be learned here
i still learn something every few days from this discord alone
Sun bearOP
yeah this wasnt the server I was admonished in , it was the Laravel server from one of the top guys
which really made me angry because it resulted in me being muted for a week simply because there were 3 people trying to help me, and one of them was him who I had known previously was aggressive , and then he said "hes out" and then came back and antagonized me and i got muted for saying please leave i dont want this kind of help
and the other mod was right there, being helpful, but then siding with that guy
i have little interest in discord politics
i truly appreciate your atittude
and your help in this matterr
@Sun bear and your help in this matterr
no problem 🙂
Sun bearOP
i tried sendin ya a friend request but youre not accepting them, which i respect cause I have my own boundaries im drawing on online - but i may look ya up if I need any more advice
Sun bearOP
appreciate it brotha, and yeah i know about those scams. I call them out when they try to play em on me
the random "hey blah blah filed the work paper" "oops wrong number"
"wanna be friends??"
me and my wall street buddy joked about it, im a firm non-crypto person but im fine with my friends views on it because theyre realistic
anyway, i gotta get back to what im doing, thank you again, i look forward to chattin more in the future!