Next.js Discord

Discord Forum

Cors error

Unanswered
Sokoke posted this in #help-forum
Open in Discord
SokokeOP
I have next js cors error.
I have a Nextjs project.
when another project(HTML frontend) call nextjs project API using fetch, cors error encoutered.
who could help me to fix this?

- Next API code
import { NextRequest, NextResponse } from "next/server"
import type { NextApiRequest, NextApiResponse } from 'next'
import { v4 as uuidv4 } from 'uuid'
import NextCors from "nextjs-cors"

const sessions = new Map()

export async function POST(req: NextApiRequest, res: NextApiResponse) {

await NextCors(req, res, {
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
origin: '*',
optionsSuccessStatus: 200,
});

return NextResponse.json({ status: 200 })
}

- HTML frontend Code
(function() {
const url = 'http://localhost:3000/api/track';
const data = {
page: window.location.pathname,
referrer: document.referrer,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
};

fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).catch(err => console.error('Analytics tracking failed', err));
})()

0 Replies