Reputation: 41
NextJs version : 13.4.3
I created a route handler to capture a POST request. Route handler doc : [https://nextjs.org/docs/app/building-your-application/routing/router-handlers]
In this handler, I only redirect to an url of my website.
Code :
import { type NextRequest } from 'next/server';
import { redirect } from 'next/navigation';
export async function POST(request: NextRequest) {
// Delete "api" in the url
const newUrl = request.url.replace('/api', '');
redirect(newUrl);
}
Error : When a POST request is captured, I'm redirecting but I get a Next 405 error code
If I replace the url of my website by another random url like (facebook.com, google.com, whatever.com), it works perfectly without getting an error.
Could it be because my site does not support 302 redirections?
Thanks in advance !
Upvotes: 1
Views: 4558
Reputation: 64
This route did work (next v13.4.12):
import { NextRequest, NextResponse } from "next/server";
export async function POST({ nextUrl: { origin } }: NextRequest) {
/**
* 1)
* NextResponse.redirect requires an absolute url.
* "origin" is used here to get protocol, host and port. For instance
* origin of http://localhost:3000/api/foo is "http://localhost:3000"
*
* 2)
* status should be 303, browser will redirect with method GET, see
* MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303
*/
return NextResponse.redirect(`${origin}/bar`, { status: 303 });
}
Upvotes: 2
Reputation: 41
It seems to be because Next uses code 307 and 308 for redirects. However, only a redirect with code 302 can transform a POST request into a GET request. I tried :
Response.redirect('url', 302)
but got the same error.
I had to use a Clouflare worker to get it to work. The POST request is sent to the worker url, and the worker redirects to an url in my application (https://developers.cloudflare.com/workers/)
Upvotes: 0