node.jsexpresscors

How do I fix this cors error when attempting to host on vercel


I am trying to deploy and host my app on vercel. I have checked my development server and my app works perfectly fine however on vercel I get :

about:1 Access to XMLHttpRequest at 'https://portfolio-beryl-eight-48.vercel.app/api/github/fetch-profile' from origin 'https://ckolaportfolio.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

const config = require('./utils/config')
const express = require('express')
const app = express()
const cors = require('cors')
const middleware = require('./utils/middleware')
const githubRouter = require('./controllers/github')


app.use(cors());
app.use(express.static('dist'))
app.use(express.json())
app.use(middleware.requestLogger)

app.use('/api/github', githubRouter)


app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)

module.exports = app

I have included cors as seen above and I still do not understand why it is failing I have also included this vercel.json in my backend directory

{
    "version": 2,
    "builds": [
        {
            "src": "index.js",
            "use": "@vercel/node"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "index.js"
        }
    ],
    "headers": [
        {
            "source": "/api/(.*)",
            "headers": [
                {
                    "key": "Access-Control-Allow-Origin",
                    "value": "https://ckolaportfolio.vercel.app"
                },
                {
                    "key": "Access-Control-Allow-Methods",
                    "value": "GET, POST, OPTIONS"
                },
                {
                    "key": "Access-Control-Allow-Headers",
                    "value": "Content-Type, Authorization"
                }
            ]
        }
    ]
}

what could I possibly be missing? I have included environment keys in my backend on vercel.

require('dotenv').config()

const PORT = process.env.PORT
const GITHUB_TOKEN = process.env.GITHUB_TOKEN
const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim())
const NODE_ENV = process.env.NODE_ENV || 'development'
const FRONTEND_URL = process.env.FRONTEND_URL || 'https://ckolaportfolio.vercel.app'

module.exports = {
    PORT,
    GITHUB_TOKEN,
    ALLOWED_ORIGINS,
    NODE_ENV,
    FRONTEND_URL
}

that is my config.js above

This is the request headers I have and the response headers are 0


Solution

  • I got the same error around 6 months ago, it was happening because i was hosting both the backend and the frontend on the same server and here is how i fixed it: Here is the vercel config file for the frontend:

    {
      "rewrites": [
        {
          "source":"/(.*)",
          "destination": "/index.html"
        }
      ]
    }
    

    and the config file for the backend:

    {
      "version": 2,
      "builds": [
        {
          "src": "index.js",
          "use": "@vercel/node"
        }
      ],
      "routes": [
        {
          "src": "/api/(.*)",
          "dest": "index.js"
        }
      ]
    }
    

    Note that i needed to host on different servers (bold so you don't miss it). I tried playing with CORS but it turned out not to be the cause of the problem. I suppose that you tried to find on the internet but couldn't find anything (as i did during days for this problem ; )). I don't really know if it fits your project but i let you adapt because you must understand how it will fit your project better than me. If i misunderstood something about what you said, feel free to let me know, i would be glad to help.