js sending a 307Next.js 13 redirect with different http method

I have Next.js route handler which is called by external payment API with POST method to redirect after payment. Inside that route handler I redirect user to different page. As a result user is actually redirected to the page but with POST method and no page is displayed, just 405 browser error page. I need to redirect user from POST route handler to another URL with GET method to get the page content. How do i do that in Next.js 13?

Here is my code

import { env } from "@/env.mjs";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
    return NextResponse.redirect(new URL(`${env.NEXT_PUBLIC_SITE_URL}/catalog`));
}

Also here are headers

enter image description here

Upvotes: 1

Views: 2585

Answers (1)

I found some useflul information in documentation about redirects with initial method saving.

Why does Next.js use 307 and 308? Traditionally a 302 was used for a temporary redirect, and a 301 for a permanent redirect, but many browsers changed the request method of the redirect to GET, regardless of the original method. For example, if the browser made a request to POST /v1/users which returned status code 302 with location /v2/users, the subsequent request might be GET /v2/users instead of the expected POST /v2/users. Next.js uses the 307 temporary redirect, and 308 permanent redirect status codes to explicitly preserve the request method used.

By default Next.js uses 307 and 308 statuses for temporary and permanent redirects to prevent changing HTTP method from current method to GET method how it has been in 301 and 302 status (older redirect statuses). So to prevent saving method I updated my code to redirect with status 302 so it automatically changes method to GET.

Here is updated code:

import { env } from "@/env.mjs";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
    return NextResponse.redirect(newURL(`${env.NEXT_PUBLIC_SITE_URL}/catalog`), 302);
}

Upvotes: 2

Related Questions