Next.js Discord

Discord Forum

Redirect in route.ts

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hi, I'm working on my app and I would like to implement a stripe checkout. I have a form with POST method which calls /api/basic route and inside the route.ts I'm creating stripe session etc, what I'm getting back is
session.url
and I'm not able to redirect it to the page correctly. I'm getting 403 error. I've tried using
redirect
from 'next/navigation' but it't not working, also I've tried
return NextResponse.redirect(session.url)
with no luck.

8 Replies

Since you're leaving next.js world all together, this is what I do when redirecting to stripe, just use javascript :

window.location.href = session.url
Cape lionOP
yes but this is on server side, I mean /api/directory/route.ts
in this case window is not defined
Jumbo flying squid
You should return the checkout url as result of your api endpoint
Then when you receive that response clientside you should do what @andrewscofield said
Ooh right, I assumed you were already on client side. Yes what @Jumbo flying squid said is 100% correct.
Haddock
that worked for me as well. i still can't figure out why i wasn't able to use redirect(url).

try {
    console.log(
      "redirecting to stripe onboarding page",
      data.onboardingUrl
    );

    // redirect(data.onboardingUrl); // DIDNT WORK!
    window.location.href = data.onboardingUrl; // Works
  } catch (error) {
    console.error("Error during redirection:", error);
  }

I kept getting this error:

app-index.js:31 Error during redirection: Error: NEXT_REDIRECT
at getRedirectError (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect.js:40:19)
at redirect (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect.js:50:11)
at handleStartStripeConnectOnboarding (webpack-internal:///(app-pages-browser)/./app/creator/become-creator-client.tsx:111:74)