Member-only story
Solving CORS and API Issues in Nuxt 3 on Netlify

I recently experienced first hand that deploying a Nuxt 3 application to Netlify with internal API endpoints can be quite challenging, especially when dealing with CORS (Cross-Origin Resource Sharing) errors, routing mismatches, and Netlify function configurations. Hopefully, this article can help you a bit when dealing with the above.
I’ll try to explain step-by-step on how to address these issues, ensuring smooth API communication both locally and in production. By setting up middleware, configuring Netlify correctly, and dynamically handling CORS headers, you can overcome common obstacles, just like i did, but without the headaches
The Problem
When deploying a Nuxt 3 application to Netlify, you might run into these issues:
- CORS Errors: API calls from a different domain fail due to CORS restrictions, preventing proper data exchange.
- Routing Issues: Requests to
/api/*
routes may trigger Vue Router warnings, such as:[Vue Router warn]: No match found for location with path "/api/searchfoodName=jord&token=..."
- Netlify Function Mapping: Redirects for API requests might not properly route to the serverless function, causing deployment errors or unexpected behavior.
Lets dive into the different solutions
Now, my problem was that I had 2 different Nuxt applications. One, which exposed internal API’s and another application on a different domain that needed to use the exposed API. I ran into Cors issues. So lets dive into what you can do to resolved these issues:
Step 1: Handling CORS in Nuxt 3
Nuxt 3, powered by Nitro, makes it straightforward to manage CORS at the server level. First, you need to update your API handler (e.g., server/api/search.get.js
) with the following code:
export default defineEventHandler(async (event) => {
const origin = getRequestHeader(event, "origin") || "*";
// Handle preflight OPTIONS request
if (event.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": "GET, POST, OPTIONS"…