Next.JS application which works locally but not works on CloudFlare pages

289 views Asked by At

I have a Next.JS application with API routes which has simple mongoDB queries. Everything working perfectly locally, but when it's deployed to CloudFlare pages, API requests are not working, it gives POST https://[my-url]/api/checkUser 405 (Method Not Allowed). Can someone help me to solve this issue? Thanks!

I also added these headers to next.config.js too.

async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
          { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }

I already enables CORS, but it doesn't helped to solve the issue.

here's pages/api/checkUser.ts

import type { NextApiRequest, NextApiResponse } from 'next'
import Cors from 'cors'
import { MongoClient } from 'mongodb';

// Initializing the cors middleware
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
const cors = Cors({
    methods: ['POST', 'GET', 'HEAD'],
})

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(
    req: NextApiRequest,
    res: NextApiResponse,
    fn: Function
) {
    return new Promise((resolve, reject) => {
        fn(req, res, (result: any) => {
            if (result instanceof Error) {
                return reject(result)
            }

            return resolve(result)
        })
    })
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    await runMiddleware(req, res, cors)
    if (req.method === 'POST') {

        const client = new MongoClient(process.env.MONGODB_URI);

        await client.connect();
        const db = client.db();

        const newPost = req.body;
        // Check if a record with the same custom _id already exists
        const existingDoc = await db.collection('StoreUsers').findOne({ _id: newPost._id });

        if (existingDoc) {
            res.status(200).json({ ok: true });
        } else {
            res.status(204).json({ ok: false });
        }

        await client.close();
    } else {
        // Handle other HTTP methods (e.g., GET, PUT, DELETE) if needed
        res.status(405).end(); // Return "Method Not Allowed" for unsupported methods
    }
}

This is how I called the API.

const validateUser = async (id) => {
        try {
            const response = await axios.post('api/checkUser', { _id: id })
            return response?.data?.ok;
        } catch (error) {
            console.error('Error while checking user\'s KYC:', error);

        }
    }

I also tried with Fetch API but the error remains same.

0

There are 0 answers