0

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

2
  • Share the exact request being made, then find the OPTIONS request in the network tab and share the HTTP response headers that came back from the server for the request that failed. Commented Dec 24, 2024 at 3:52
  • @Evert I have added a screenshot of my request please take a look Commented Dec 24, 2024 at 7:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your input it actually worked out I do not know why I failed the first time trying it your way but doing it now again it finally worked.👌
0

I had this CORs issue for awhile, I tinkered with various settings and configs with redeployments to test production, it was a pain in the a!$@ and probably would've left a lot more margin for errors. I eventually settled on my own solution of not trying to manage one monolithic full-stack application.

I separated and hosted both frontend/backend on Vercel, this took 10 minutes and provided alot of benefits:

  • My backend codebase is completely separate, with one very distinct responsibility.
  • My logs are not bloated with frontend events.
  • My backend codebase is small, specific and leaves my frontend codebase slimmer with less potential for arbitrary errors.
  • Vercel supports serverless functionality so my backend is not resource intensive.

Just remember, if you attach a domain to your frontend, you should be sending requests to the domain that is assigned by Vercel, not your custom domain.

const response = await fetch(${API_BASE_URL}/<endpoint>, options);

Hope this helps or sheds some light on other possibilities for this CORs issue.

Backend & Frontend

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.