Webhook revalidate gives 405 Method not allowed and form 404 when submitting after Internationalization implemented on the site

Hi, I have added internationalization as per a blog post using Next.js. Since then the webhook for revalidate every time there is an update on the CMS stopped working with an error 405. Also, the contact form now gives an error 404 on localhost, and 405 on prod when submitting and this was working fine before.

I have read countless of post from Prismic, GitHub and Stackeoverflow but none offered me a solution. This has been for a week already.

I dicovered th errors while seeing that the update wasn't imediatly on the site after updating the CMS. Errors I am having are 405 on the Webhook and a POST 404/405 when submitting the contact form.
https://jam.dev/c/1935640f-4628-4ed0-a329-a0fb96785aff

response of form submission:
Uploading: image.png…

localaly, it gives me 404:
image

However, on the Vercel logs tab I can see a 200 for the form submission even though it didn't submit:

Role

I am the solo developer of the site.

Host

Vercel

Package.json file:

"dependencies": {
"@prismicio/client": "^7.3.1",
"@prismicio/next": "^1.5.0",
"@prismicio/react": "^2.7.3",
"@types/node": "^20.8.9",
"@types/react": "^18.2.33",
"@types/react-dom": "^18.2.14",
"@vercel/speed-insights": "^1.0.12",
"clsx": "^2.1.0",
"framer-motion": "^11.0.6",
"next": "^14.2.7",
"nodemailer": "^6.9.13",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"swiper": "^11.0.7",
"tailwind-merge": "^2.2.1",
"typescript": "^5.2.2"
},

Steps to reproduce

You may have to login on the CMS to debug, Also, I can send a link to the repository.

1 Like

Hi @joa_palacios ,

Welcome to to the community, I'll be happy to help :slight_smile:

What error details/logs are you seeing in the webhooks screen?

Can you show me the code in your /send route?

Thanks.

1 Like

Hi @Phil below is a screenshot where you can see the logs of the Webhook:

See below the code for the api/send:

/**
 * @name POST
 * @description Handles contact form submissions and sends an email with the provided information
 * @param {NextRequest} req - Request object containing contact form data
 * @param {NextResponse<Response>} res - Response object to send HTTP response
 * @returns {Promise<void>}
 */

export type Fields = {
	name: string;
	message: string;
	email: string;
	subject: string;
};

export type Response = {
	error?: string;
	status?: string;
	message?: string;
};

import { NextRequest, NextResponse } from 'next/server';

import nodemailer from 'nodemailer';

/**
 * @description Nodemailer transporter configuration for sending emails
 * @returns {void}
 */

const transporter = nodemailer.createTransport({
	service: 'Gmail',
	auth: {
		user: process.env.EMAIL_ADDRESS,
		pass: process.env.EMAIL_PASSWORD,
	},
});

transporter.verify(function (error, success) {
	if (error) {
		console.error(error);
	} else {
		console.log('Server is ready to take our messages');
	}
});

export const POST = async (req: NextRequest, res: NextResponse<Response>) => {
	const request = await req.json();
	const { name, email, message, subject } = request as Fields;

	if (req.method !== 'POST') {
		return request.status(404).send({ status: 'fail', error: 'Begone.' });
	}

	try {
		if (!name || !name.trim()) {
			throw new Error('Please enter your name.');
		}

		if (!email || !email.trim()) {
			throw new Error('Please enter your email address.');
		}

		if (!subject || !subject.trim()) {
			throw new Error('Please enter a subject');
		}

		if (!message || !message.trim()) {
			throw new Error('Please enter a message');
		}

		await transporter.sendMail({
			...
		});

		return new Response(JSON.stringify({ status: 'done' }), {
			headers: {
				'content-type': 'application/json',
			},
		});
	} catch (error) {
		return new Response(JSON.stringify({ status: 'fail', error: `${error}` }), {
			headers: {
				'content-type': 'application/json',
			},
		});
	}
};

It seems like the issues you're facing with the webhook and contact form are likely related to the internationalization setup you implemented. Here are some steps and considerations to help you troubleshoot and resolve these issues:

Potential Issues and Solutions

  1. Locale-Prefixed Routes:

    • Your middleware might be redirecting API routes to locale-prefixed routes, which could cause the 405 Method Not Allowed error if the locale-prefixed route only allows GET requests.
    • Ensure that your middleware is not affecting API routes. You can modify your middleware to skip API routes.
    // Example middleware modification to skip API routes
    export function middleware(request) {
      const { pathname } = request.nextUrl;
      const isApiRoute = pathname.startsWith('/api');
    
      if (isApiRoute) {
        return NextResponse.next();
      }
    
      // Your existing locale handling logic
    }
    
  2. Disabling Automatic Locale Detection:

    • If automatic locale detection is causing issues, you can disable it in your next.config.js.
    // next.config.js
    module.exports = {
      i18n: {
        localeDetection: false,
      },
    };
    
  3. Check Route Handlers:

    • Ensure that your route handlers are correctly set up to handle POST requests. The provided code snippet for the contact form seems to have a check for the request method, but it should be placed before parsing the request body.
    export const POST = async (req: NextRequest, res: NextResponse<Response>) => {
      if (req.method !== 'POST') {
        return new Response(JSON.stringify({ status: 'fail', error: 'Begone.' }), {
          status: 405,
          headers: {
            'content-type': 'application/json',
          },
        });
      }
    
      const request = await req.json();
      const { name, email, message, subject } = request as Fields;
    
      // Your existing validation and email sending logic
    };
    
  4. Vercel Logs:

    • Since you mentioned seeing a 200 status in Vercel logs, it might be worth checking if there are any redirects or rewrites configured in your Vercel project that could be affecting the routes.

Additional Considerations

  • Localhost vs. Production:

    • Ensure that your environment variables (e.g., EMAIL_ADDRESS, EMAIL_PASSWORD) are correctly set up in both your local and production environments.
  • Error Handling:

    • Improve error handling in your route handlers to provide more detailed error messages, which can help in debugging.

Summary

  • Modify your middleware to skip API routes.
  • Consider disabling automatic locale detection if it's causing issues.
  • Ensure your route handlers are correctly set up to handle POST requests.
  • Check Vercel logs and configurations for any redirects or rewrites affecting the routes.

If you need further assistance, please provide more details about your middleware setup or any specific error messages you are seeing.

Best regards.

1 Like

Thanks for your support @Phil
The first advised solution about the middleware did the trick. It seemed that the middleware was afecting the path of the api.

1 Like