Next.js error 405 method not allowed on redirect after form submission (POST)

Viewed 340

I submit a form (POST method) to a next.js API route. I handle the content of the body (store the content of the form) then I want to redirect to a thank you page.

The API route looks like this

export default async function handler(req, res) {
    const body = Object.assign({}, req.body)
    
    // ... do stuff
    
    res.redirect(307, "/thank-you")

When the redirect occurs, I get a flash of an error page with code 405.

1 Answers

Apparently, next.js looks at the status code passed to the redirect function. I got the hint after reading this.

So, the solution was just to change the status code from the redirect function:

res.redirect(302, "/thank-you")
Related