CORS Issue on only some API calls

I have multiple API calls on my project deployed to vercel but only some of them face CORS issues, for example:
import { db } from "../../lib/db";

export async function GET() {
const start = performance.now();

try {
const posts = await db.subjects.findMany({
select: {
id: true,
name: true,
},
});
const end = performance.now();
console.log(`API call took ${end - start} milliseconds`);
return new Response(JSON.stringify(posts));
} catch (error) {
return new Response(null, { status: 500 });
}
}
import { db } from "../../lib/db";

export async function GET() {
const start = performance.now();

try {
const posts = await db.subjects.findMany({
select: {
id: true,
name: true,
},
});
const end = performance.now();
console.log(`API call took ${end - start} milliseconds`);
return new Response(JSON.stringify(posts));
} catch (error) {
return new Response(null, { status: 500 });
}
}
works perfectly fine however
import { db } from "../../lib/db";

const headers = {
"Access-Control-Allow-Origin": "https://examvault.vercel.app",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};

export async function GET(request: Request) {
try {
const url = new URL(request.url);
const name = url.searchParams.get("name") || "";
console.log("Received subject name:", name);

const subjects = await db.topic.findMany({
where: {
name: {
equals: name,
},
},
select: {
id: true,
},
});

if (subjects.length === 0) {
return new Response(null, { status: 404 });
}

const { id } = subjects[0];

const headers = {
"Access-Control-Allow-Origin":
"https://examvault-danielarbabian.vercel.app",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "Content-Type",
};

return new Response(JSON.stringify(id));
} catch (error) {
return new Response(null, { status: 500 });
}
}
import { db } from "../../lib/db";

const headers = {
"Access-Control-Allow-Origin": "https://examvault.vercel.app",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};

export async function GET(request: Request) {
try {
const url = new URL(request.url);
const name = url.searchParams.get("name") || "";
console.log("Received subject name:", name);

const subjects = await db.topic.findMany({
where: {
name: {
equals: name,
},
},
select: {
id: true,
},
});

if (subjects.length === 0) {
return new Response(null, { status: 404 });
}

const { id } = subjects[0];

const headers = {
"Access-Control-Allow-Origin":
"https://examvault-danielarbabian.vercel.app",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "Content-Type",
};

return new Response(JSON.stringify(id));
} catch (error) {
return new Response(null, { status: 500 });
}
}
doesn't work when visiting the production URL despite the first one working. I get this error: Access to XMLHttpRequest at 'http://localhost:3000/api/fetchtopicid?name=electricity' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Solution:
```ts //You can do it like this. export async function GET(request: Request) { return new Response('Hello, Next.js!', {...
Jump to solution
10 Replies
Maj
Maj17mo ago
U can try with "Access-Control-Allow-Origin": "*" to see if its working
wlvz
wlvz17mo ago
didn't work sadly, what confuses me is that the api call withou any CORS configuration works but the second one doesn't work
Maj
Maj17mo ago
did you try it without cors headers?
wlvz
wlvz17mo ago
yeah, still didn't work
Maj
Maj17mo ago
you probably need a cors middleware then. if you make const headers variable will that automaticly append it to the headers?
Maj
Maj17mo ago
Stack Overflow
NextJs CORS issue
I have a Next.js app hosted on Vercel at www.example.com, which needs to communicate with a backend .NET Core Web API hosted on a different server at api.example.com. The .NET core web api has been
Maj
Maj17mo ago
check the first answer.

// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
};

// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
};
Maj
Maj17mo ago
GitHub
How to enable cors in Nextjs 13 Route Handlers · vercel next.js · D...
Summary Hi all I would like to define CORS to allow any origin for development purposes with Nextjs 13 route handlers. I tried the following options, but they did not work: In the route handler its...
Solution
Maj
Maj17mo ago
//You can do it like this.
export async function GET(request: Request) {
return new Response('Hello, Next.js!', {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
}
//or you can make a middleware if you hit the api endpoint it will append the headers
export async function middleware(request: NextRequest) {
const response = NextResponse.next()

if (request.nextUrl.pathname.startsWith("/api")) {
response.headers.append("Access-Control-Allow-Origin", "*")
}
//...
return response
}
//You can do it like this.
export async function GET(request: Request) {
return new Response('Hello, Next.js!', {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
}
//or you can make a middleware if you hit the api endpoint it will append the headers
export async function middleware(request: NextRequest) {
const response = NextResponse.next()

if (request.nextUrl.pathname.startsWith("/api")) {
response.headers.append("Access-Control-Allow-Origin", "*")
}
//...
return response
}
wlvz
wlvz17mo ago
this worked 🙏, tysm
Want results from more Discord servers?
Add your server