I’m working on a React.js/Next.js project that utilizes Google reCAPTCHA. My frontend seems to be working (I know because I’ve set up print statements along the way), but the backend is giving me this error in my local terminal:
error – No HTTP methods exported in ‘srcappapirecaptcharoute.ts’. Export a named export for each HTTP method.
I’m also getting an error in my dev tools:
‘POST http://localhost:3000/api/recaptcha 405 (Method Not Allowed)’
Which I believe is related to the other error.
Here is the code:
import { NextApiRequest, NextApiResponse } from 'next';
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import axios from 'axios';
const app = express();
app.use(cors());
app.use(bodyParser.json());
console.log('hi');
export async function postHandler(req: NextApiRequest, res: NextApiResponse){
if (req.method === 'POST') {
const { token } = req.body;
try {
const response = await axios.post(
`https://www.google.com/recaptcha/api/siteverifysecret=${process.env.NEXT_PUBLIC_RECAPTCHA_SECRET_KEY}&response=${token}`
);
console.log('you made it here');
if (response.data.success) {
res.status(200).json({ message: 'reCAPTCHA verification successful' });
} else {
res.status(400).json({ message: 'reCAPTCHA verification failed' });
}
} catch (err) {
console.log(err);
res.status(500).json({ message: 'Internal server error' });
}
};
}
I’ve tried renaming the function, exporting it as const, and exporting at the end of the file rather than when it’s named.
2
Answers
In the
app
folder, Route Handlers should be defined asexport async function METHOD() {}
, whereMETHOD
can beGET
,POST
,PUT
, etc. For aPOST
, for example, it should be:If you are using NextJS 13
App Router
then use this code below:File:
./app/api/recaptcha/route.ts
If you are using NextJs 13
Page Router
then use this:File:
./pages/api/recaptcha.ts
Hopefully this will fix your issues 🙂