Skip to content
Avatar of vercelvercel/examples

CORS in Edge Functions

Handle CORS at the edge.

Framework
Placeholder Thumbnail Image

CORS Example

Below is the code from pages/api/hello.ts:

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

Test it out with:

curl -i -X OPTIONS -H 'origin: https://vercel.com' https://edge-functions-cors.vercel.sh/api/hello

Demo

https://edge-functions-cors.vercel.app/api/hello

How to Use

You can choose from one of the following two methods to use this repository:

One-Click Deploy

Deploy the example using Vercel:

Clone and Deploy

Download this repository via git:

git clone https://github.com/vercel/examples.git

Execute create-next-app with pnpm to bootstrap the example:

pnpm create next-app --example https://github.com/vercel/examples/tree/main/edge-functions/cors cors

Next, run Next.js in development mode:

pnpm dev

Deploy it to the cloud with Vercel (Documentation).

Placeholder Thumbnail Image
Avatar of vercelvercel/examples

CORS in Edge Functions

Handle CORS at the edge.

Framework

CORS Example

Below is the code from pages/api/hello.ts:

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

Test it out with:

curl -i -X OPTIONS -H 'origin: https://vercel.com' https://edge-functions-cors.vercel.sh/api/hello

Demo

https://edge-functions-cors.vercel.app/api/hello

How to Use

You can choose from one of the following two methods to use this repository:

One-Click Deploy

Deploy the example using Vercel:

Clone and Deploy

Download this repository via git:

git clone https://github.com/vercel/examples.git

Execute create-next-app with pnpm to bootstrap the example:

pnpm create next-app --example https://github.com/vercel/examples/tree/main/edge-functions/cors cors

Next, run Next.js in development mode:

pnpm dev

Deploy it to the cloud with Vercel (Documentation).

Unleash New Possibilities

Deploy your app on Vercel and unlock its full potential