Next.js Discord

Discord Forum

How to redirect from route handler using Next 13?`

Unanswered
Griffon Nivernais posted this in #help-forum
Open in Discord
Griffon NivernaisOP
At the moment I have the following:
    const result = await database.fetchRedirectUrl(params.lookupKey);
    const redirectUrl = result ? result.url : env.DOMAIN; // string
    console.log(params.lookupKey, asText, redirectUrl);

    res.redirect(307, redirectUrl).end();

The following error appears to be spammed:
API resolved without sending a response for /api/redirect/aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbQ==, this may result in stalled requests.

How can I remedy this exactly?

26 Replies

@riský in route handlers, you should use NextResponse.redirect: <https://nextjs.org/docs/app/api-reference/functions/next-response#redirect>
Griffon NivernaisOP
I might have made a mistake in referencing what I'm using because it seems to have given me this error:
Error: API route returned a Response object in the Node.js runtime, this is not supported. Please use `runtime: "edge"` instead: https://nextjs.org/docs/api-routes/edge-api-routes
I haven't migrated over to app router, I'm using the pages router in this project and still use res.x and the like.
ohh ok route hander is the app dir term
Griffon NivernaisOP
I'm sorry lol still getting them mixed up.
so i got a little confused
Griffon NivernaisOP
Edited the tags so it should be a bit clearer, I might end up migrating to Next 14 if there's no real solution to this though.
btw next 14 != app dir
where are you getting the error from?
Griffon NivernaisOP
Of course yeah, I'm mentioning Next 14 as it's focused on stability - this could be a pre-existing error that was resolved in the next major version.

Local development environment, if it helps the URL usually follows this format: http://192.168.0.236:3000/api/redirect/aHR0cHM6Ly9uZXh0anMub3JnL2RvY3MvYXBwL2FwaS1yZWZlcmVuY2UvZnVuY3Rpb25zL25leHQtcmVzcG9uc2UjcmVkaXJlY3Q=
ohh ok i see what you are doing
but i really haven't seen this before in my pages dir times 😭
Griffon NivernaisOP
Hmm, how odd.
I'll try Next 14 and see if that helps.
but what occures if you don't have the .end
and im guessing the console.log works
Griffon NivernaisOP
Console.log works yes, same thing essentially.
Griffon NivernaisOP
Same issue even in Next 14, unsure if migrating to the app router would help either at this point.
Will try to make a reproducible environment.
I have something here, it reflects pretty much exactly what I'm doing at a minimal scale: https://stackblitz.com/edit/stackblitz-starters-qvxsvi?file=pages%2Fapi%2Fredirect.ts
Griffon NivernaisOP
Bump.
Griffon NivernaisOP
lol I'm an idiot.
Well I'm not but you'll think I am, the short of it is I had the application redirect to itself because of a wonky database row. Go me.
Wonderful.
Thanks for your time Risky! 💞