#CORS issue with serverless function.

1 messages · Page 1 of 1 (latest)

neat wedgeBOT
#

Hi @timber acorn. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It seems you have already set CORS headers on a Response as shown in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/router-handlers). However, please note that Cache-Control headers cannot be set using next.config.js or vercel.json files, as mentioned in the Vercel documentation (https://vercel.com/docs/concepts/functions/edge-caching).

To set CORS headers in your Next.js API route, you can use the following example:

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',
    },
  });
}

If you're still facing issues, you can try handling CORS at the edge using the edge-functions-cors (https://vercel.com/templates/next.js/edge-functions-cors) template. Here's an example of how to handle CORS in an Edge Function:

import { NextRequest } from 'next/server'
import cors from '../../lib/cors'

export const config = {
  runtime: 'edge',
}

export default async function handler(req: NextRequest) {
  // `cors` also takes care of handling OPTIONS requests
  return cors(
    req,
    new Response(JSON.stringify({ message: 'Hello World!' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    })
  )
}

If you're using Vercel for deployment, make sure to configure CORS for production (https://vercel.com/templates/next.js/blog-next-sanity) by adding your production URL to the list of CORS origins:

npm --prefix studio run cors:add -- [your production url] --credentials
Vercel Documentation

Vercel Serverless Functions enable running code on-demand without needing to manage your own infrastructure, provision servers, or upgrade hardware.

Handle CORS at the edge.

A statically generated blog example using Next.js and Sanity