Next.js Discord

Discord Forum

Redirect to a different site

Answered
Spectacled Caiman posted this in #help-forum
Open in Discord
Spectacled CaimanOP
In the API router. How can I redirect a user to a completely different site? When the user access a route with a specific id. I grab that id, check the database, find a redirect url that matches that entry, and then I need to redirect the user. What should I do?
Answered by riský
View full answer

25 Replies

can you not use redirect to go to 3rd party site?: https://nextjs.org/docs/app/api-reference/functions/redirect
Spectacled CaimanOP
In the API routes
like route.ts?
Spectacled CaimanOP
yep
you can still do it (just make sure to return the redirect)
@riský you can still do it (just make sure to return the redirect)
Spectacled CaimanOP
Alright let me try that
I get this error:
Error: NEXT_REDIRECT
    at getRedirectError (webpack-internal:///(rsc)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/client/components/redirect.js:40:19)
    at redirect (webpack-internal:///(rsc)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/client/components/redirect.js:50:11)
    at GET (webpack-internal:///(rsc)/./src/app/api/r/[code]/route.ts:22:73)
    at async eval (webpack-internal:///(rsc)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/future/route-modules/app-route/module.js:254:37) {
  digest: 'NEXT_REDIRECT;replace;https://randomsite.com',
  mutableCookies: ResponseCookies {
    _parsed: Map(0) {},
    _headers: HeadersList {
      [Symbol(headers map)]: Map(0) {},
      [Symbol(headers map sorted)]: Map(0) {}
    }
  }
}
you are having a try catch... next's redirect actually throws an "error" to work
Answer
Spectacled CaimanOP
Oh shit it works thanks
I didn't know it throws an error to work
its the best way to cancel the rest of the code and just redirect without return tbh (can be done anywhere)
@Spectacled Caiman Oh shit it works thanks
so, you can redirect to 3rd pary website now? :derp:
@riský you can just use [NextResponse.redirect](<https://nextjs.org/docs/app/api-reference/functions/next-response#redirect>)
Spectacled CaimanOP
But I have to do the new URL stuff and I don't like it
can you not just do a string like the other redirect (i haven't used it in a while)
@riský can you not just do a string like the other redirect (i haven't used it in a while)
Spectacled CaimanOP
Yeah I think so but that also throws an err to redirect no?
Btw this thank you u very much
@Spectacled Caiman Yeah I think so but that also throws an err to redirect no?
no, they are 2 different redirect methods (one works for both pages and api routes, and other only works here)
Spectacled CaimanOP
Ag okay then I guess I can’t give it a string because I got an error when I tried that
ohh ok then 😭
but you have your code working, so that good ig :derp:
Spectacled CaimanOP
Yeah 💀
Thanks again